支持自部署需求管理、交付流程与飞书集成

This commit is contained in:
xyt committed 2026-11-25 12:40:33 +08:00
1 parent 4556a5b483
commit e22b66d9dd
148 files changed
+8297 -6390

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
node_modules
.next
.git
.env*
!.env.example
data
backups
*.sqlite
*.sqlite-wal
*.sqlite-shm
dist
out
outputs
work
.wrangler
.vinext
.sites-runtime
.openai
.agents
.codex
coverage
tests
*.tsbuildinfo
*.log
.DS_Store
legacy
# Never include runtime bootstrap access files
INITIAL_ACCESS.txt
compose.server.yaml
# Operational staging is not application source
deploy
DEPLOYED_*.md
+32
View File
@@ -0,0 +1,32 @@
# 用户实际访问的完整 origin,不带路径或末尾斜线。
# 正式部署请填写 HTTPS 域名;本地开发可用 http://localhost:3000。
APP_URL=https://demands.example.com
# 部署在域名子路径时填写,例如 /demands;独立域名留空。变更后需重新构建。
NEXT_PUBLIC_BASE_PATH=
# 首次启动数据库时创建的管理员。密码必须至少 12 位,不提供默认密码。
INITIAL_ADMIN_USERNAME=admin
INITIAL_ADMIN_PASSWORD=
INITIAL_ADMIN_DISPLAY_NAME=系统管理员
# 非 Docker 运行时的数据目录。Docker Compose 固定使用 /app/data。
DATA_DIR=./data
# 可选:受信反向代理覆盖的单个客户端 IP 请求头,例如 x-real-ip。
# 仅在应用端口不能绕过代理访问、且代理会覆盖该请求头时启用。
# 留空时密码登录仅启用账号限流;配置后密码与飞书登录共用每来源 60 次/分钟,缺失或无效 IP 会拒绝登录。
LOGIN_CLIENT_IP_HEADER=
# 飞书登录:企业自建应用的凭证,留空时不显示飞书登录入口。
# 回调地址固定为 APP_URL + NEXT_PUBLIC_BASE_PATH + /api/auth/feishu/callback。
FEISHU_APP_ID=
FEISHU_APP_SECRET=
# 可选:仅允许指定企业的飞书账号授权。系统仍要求先绑定已有账号。
FEISHU_TENANT_KEY=
# 飞书群通知:在目标群添加「自定义机器人」并复制完整 Webhook。
# 群中会展示所有正式需求的标题、状态、操作人、开发责任人和详情链接。
FEISHU_BOT_WEBHOOK=
# 机器人开启签名校验时必填;使用关键词校验时关键词可设为「需有序」。
FEISHU_BOT_SECRET=
+18
View File
@@ -46,3 +46,21 @@ next-env.d.ts
/work/
*.tsbuildinfo
# Self-hosted private runtime state
/data/
/backups/
*.sqlite
*.sqlite-shm
*.sqlite-wal
!.env.example
# Never include runtime bootstrap access files
INITIAL_ACCESS.txt
# Local deployment records and instance configuration
/DEPLOYED_*.md
/compose.server.yaml
/deploy/*-cloudflare-realip.conf
/legacy/hosted-site-reference.json
/.openai/hosting.json
-4
View File
@@ -1,4 +0,0 @@
{
"d1": "DB",
"r2": null
}
+197
View File
@@ -0,0 +1,197 @@
# 自有服务器部署说明
本版本使用系统自有账号登录,账号和需求存储在自己的服务器。用户可使用管理员创建的账号;启用飞书后,首次飞书授权登录会自动注册普通成员账号,不需要 GPT 登录。本目录提供源码和部署配置。
## 1. 准备服务器
- 一台支持 Docker Engine 与 Docker Compose 插件的服务器。
- 一个解析到服务器的域名,以及对应的 HTTPS 证书和反向代理。
- 将本项目目录复制到服务器,例如 `/opt/demand-center`。不要复制 `node_modules`、`.next` 或旧托管环境的配置、凭据与缓存。
此版本使用单机 SQLite,运行一个应用实例,数据卷应位于服务器本地磁盘。不要将同一个 SQLite 数据库放在网络共享盘并由多台应用服务器写入。
## 2. 配置环境
在项目目录运行:
```sh
cp .env.example .env
chmod 600 .env
```
编辑 `.env`:
| 变量 | 填写方式 |
| --- | --- |
| `APP_URL` | 用户实际访问的 origin,例如 `https://demands.example.com`,不带路径或末尾斜线。 |
| `INITIAL_ADMIN_USERNAME` | 初始管理员用户名,例如 `admin`。 |
| `INITIAL_ADMIN_PASSWORD` | 自行生成的至少 12 位强密码,不能为空,没有默认密码。 |
| `INITIAL_ADMIN_DISPLAY_NAME` | 管理员在页面显示的姓名。 |
| `DATA_DIR` | 直接用 Node 运行时的数据目录;Compose 固定使用容器内 `/app/data`。 |
| `LOGIN_CLIENT_IP_HEADER` | 可选的受信代理客户端 IP 头,例如 `x-real-ip`。仅当代理覆盖此头、应用端口不能绕过代理访问时启用。留空只按账号限流。 |
密码包含 `$`、`#` 或空格时,在 `.env` 中用单引号包裹完整值,避免被环境文件解释。不要把真实 `.env` 提交到版本库或发给其他用户。
初始管理员仅在新数据库初始化时创建;修改环境变量不会重置已有管理员密码。后续请通过管理员页面管理账号。容器重新创建仍需保留完整环境配置。
## 3. 启动与反向代理
```sh
docker compose up -d --build
docker compose ps
docker compose logs --tail=100 app
```
健康检查通过时状态显示 `healthy`。也可以在服务器上检查:
```sh
curl --fail http://127.0.0.1:3000/api/health
```
Compose 将应用端口只绑定到服务器的 `127.0.0.1:3000`,由反向代理提供外部访问。以下 Nginx 配置以 `demands.example.com` 为例,请替换域名与证书路径:
```nginx
server {
listen 80;
server_name demands.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name demands.example.com;
client_max_body_size 22m; # 单文件 20 MB,加上上传封装开销
ssl_certificate /etc/letsencrypt/live/demands.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/demands.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
已有反向代理也需配置 `client_max_body_size 22m`(或更大),否则超过代理默认限制的附件会在到达应用前被拒绝。应用仍限制单文件不超过 20 MB。
此例假设 Nginx 直接接收用户连接,代理配置主动覆盖转发头。如果改成多层代理,需要按实际可信链路配置;不要直接相信客户端自带的转发头。
采用上面的代理配置并保持应用端口仅绑定本机后,可在 `.env` 中设置 `LOGIN_CLIENT_IP_HEADER=x-real-ip`。登录保留每账号 15 分钟最多 5 次尝试;启用来源限制后,同一来源每分钟最多 60 次尝试,其他来源的账号可继续登录。代理必须覆盖该头为单个有效 IP;缺失或无效值将拒绝登录。管理员重置密码会清除目标账号的旧锁定,来源限流仍保留。
如果 Nginx 前还有 Cloudflare,应仅信任 [Cloudflare 官方 IP 网段](https://www.cloudflare.com/ips/) 提供的 `CF-Connecting-IP`,通过 `set_real_ip_from` 和 `real_ip_header` 恢复真实来源,再覆盖传给应用的 `X-Real-IP`。不要直接将客户端可伪造的转发头当作限流依据。更换 CDN 或代理时需同步更新可信网段。
将配置放入服务器实际使用的 Nginx 配置目录后,检查并重载:
```sh
sudo nginx -t
sudo systemctl reload nginx
```
打开 `.env` 中 `APP_URL` 的地址,使用初始管理员账号登录,按提示修改初始密码,再在「账号管理」创建需要访问的业务账号。新用户用分配的用户名和密码登录,并按提示修改初始密码。管理员可以停用用户或重置密码;账号权限用于访问控制,不会赋予浏览其他用户需求的权限。
会话 Cookie 在 `APP_URL` 使用 HTTPS 时设置 Secure,请求来源校验也以该配置为准。正式启用 HTTPS 后,请通过域名访问;用服务器 IP 或 HTTP 访问不会得到同样的登录行为。应用不会用反向代理传来的身份头认定用户;账号访问由本系统控制,不再配置 ChatGPT 邀请名单。
## 4. 数据与更新
数据库为 `/app/data/demand-center.sqlite`,使用 WAL 模式。Compose 将整个 `/app/data` 持久化到 `demand_data` 命名卷。容器以 `node` 用户运行,镜像已为首次创建的数据卷设置写入权限。
```sh
docker compose up -d --build
```
更新代码后重新执行上面的命令即可重建应用,数据卷保留。请先执行下一节的备份。不要执行 `docker compose down -v`,其中 `-v` 会删除数据卷。若自行改用宿主机目录挂载,应先让该目录可由容器 UID/GID `1000:1000` 写入。
本版本已移除内置演示需求,仅显示数据库中的实际记录;按需求授权的开发方案提交与业务确认已提供;开发排期、提测和发布流转后台仍需后续建设。
## 5. 备份
`scripts/backup.mjs` 调用 [Node.js SQLite 在线备份 API](https://nodejs.org/download/release/latest-v24.x/docs/api/sqlite.html#sqlitebackupsourceDb-path-options),生成一致性快照并执行完整性检查,可以在应用运行中执行。不能直接复制运行中的主 `.sqlite` 文件作为完整备份,因为已提交的数据可能仍在 WAL 中。
先创建带时间戳的备份,再复制到宿主机:
```sh
docker compose exec -T app node scripts/backup.mjs
mkdir -p backups
docker compose cp app:/app/data/backups/. ./backups/
chmod -R go-rwx backups
```
附件内容与元数据保存在同一 SQLite 数据库中,备份与恢复会同时包含附件,不需要另行复制上传目录。脚本输出备份文件的完整路径;既有同名文件不会被覆盖。备份目录包含账号和业务数据,应限制访问,并将副本保存到独立磁盘或其他受控存储。只有数据卷内的副本不能防止磁盘或数据卷损坏。
直接使用 Node 的部署方式可运行:
```sh
node --env-file=.env scripts/backup.mjs
```
可用第二个参数指定文件名,例如 `node --env-file=.env scripts/backup.mjs ./backups/manual-2026-09-16.sqlite`。
## 6. 恢复
恢复会把账号、会话、需求和附件恢复到备份时的状态。先完成一次当前数据备份,然后将需要恢复的文件复制为项目目录中的 `backups/restore.sqlite`。
停止应用,校验备份,将当前数据库及 WAL 文件移入保留目录,再替换数据库:
```sh
docker compose stop app
docker compose run --rm --no-deps --user root -T \
--volume "$PWD/backups:/restore:ro" --entrypoint sh app -s <<'SH'
set -eu
test -f /restore/restore.sqlite
node --input-type=module -e '
import { DatabaseSync } from "node:sqlite";
const db = new DatabaseSync("/restore/restore.sqlite", { readOnly: true });
const rows = db.prepare("PRAGMA integrity_check").all();
const tables = db.prepare("SELECT COUNT(*) AS total FROM sqlite_master WHERE type = ? AND name IN (?, ?, ?)")
.get("table", "accounts", "demands", "sessions");
const ok = rows.length === 1 && rows[0].integrity_check === "ok" && tables.total === 3;
db.close();
if (!ok) throw new Error("备份完整性检查失败,未替换现有数据");
'
archive="/app/data/pre-restore-$(date +%Y%m%d-%H%M%S)"
mkdir -m 700 "$archive"
for name in demand-center.sqlite demand-center.sqlite-wal demand-center.sqlite-shm; do
if [ -f "/app/data/$name" ]; then
mv "/app/data/$name" "$archive/$name"
fi
done
cp /restore/restore.sqlite /app/data/demand-center.sqlite
chown node:node /app/data/demand-center.sqlite
chmod 600 /app/data/demand-center.sqlite
SH
```
仅在上一条恢复命令成功退出后,再启动并检查:
```sh
docker compose up -d
docker compose ps
docker compose logs --tail=100 app
```
此恢复工具容器临时使用 root 读取宿主机备份并修正文件所有者;应用服务本身仍以 `node` 用户运行。恢复前的数据保留在数据卷的 `pre-restore-时间戳` 目录中,不会自动删除。
## 7. 不使用 Docker
服务器安装 Node.js 24,使用独立的非 root 系统用户运行应用。在项目目录准备 `.env`,填好 `APP_URL` 和管理员配置,并为 `DATA_DIR` 指定有写权限的持久化目录。
```sh
npm ci
npm run build
HOSTNAME=127.0.0.1 PORT=3000 npm start
```
以上启动命令适用于 Linux。构建会生成 Next.js standalone 服务,并复制静态文件和 SOP 文档。`npm start` 加载项目根目录的 `.env` 和可选的 `.env.local` 后启动该服务;相对的 `DATA_DIR` 始终相对于项目根目录解析。
生产环境可使用 systemd 管理进程并自动重启,反向代理配置与 Docker 部署相同。保留项目目录中的构建结果、启动脚本和环境配置;不要把运行数据放进构建输出目录。
## 可选:飞书登录与群通知
按 [FEISHU.md](FEISHU.md) 配置 `FEISHU_APP_ID`、`FEISHU_APP_SECRET`、可选的 `FEISHU_TENANT_KEY`,以及 `FEISHU_BOT_WEBHOOK`、`FEISHU_BOT_SECRET`。使用项目的 Compose 配置时,修改环境变量后运行 `docker compose up -d --force-recreate` 以加载新配置。
此版本自动迁移数据库到版本 3,新增绑定、授权状态和通知表。上线前备份数据库;回滚到版本 2 应用需要恢复上线前备份,旧代码无法读取版本 3 数据库。
+32
View File
@@ -0,0 +1,32 @@
FROM node:24-bookworm-slim AS dependencies
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
FROM node:24-bookworm-slim AS builder
WORKDIR /app
ARG NEXT_PUBLIC_BASE_PATH=""
ENV NEXT_TELEMETRY_DISABLED=1 NEXT_PUBLIC_BASE_PATH=${NEXT_PUBLIC_BASE_PATH}
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:24-bookworm-slim AS runtime
WORKDIR /app
ARG NEXT_PUBLIC_BASE_PATH=""
ENV NEXT_PUBLIC_BASE_PATH=${NEXT_PUBLIC_BASE_PATH}
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
HOSTNAME=0.0.0.0 \
PORT=3000 \
DATA_DIR=/app/data
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
COPY --from=builder --chown=node:node /app/public ./public
COPY --from=builder --chown=node:node /app/content ./content
COPY --from=builder --chown=node:node /app/scripts/backup.mjs ./scripts/backup.mjs
RUN mkdir -p /app/data && chown node:node /app/data
USER node
EXPOSE 3000
CMD ["node", "server.js"]
+60
View File
@@ -0,0 +1,60 @@
# 飞书登录与群机器人接入
支持飞书首次登录自动注册、已有账号自助绑定与解绑、正式需求流转群通知、失败重试和管理员诊断。登录与通知可分别配置,默认均关闭。
## 1. 创建登录应用
1. 在[飞书开发者后台](https://open.feishu.cn/app)创建企业自建应用,开启网页应用能力。记录 App ID 和 App Secret。
2. 在安全设置中配置重定向 URL:`APP_URL + NEXT_PUBLIC_BASE_PATH + /api/auth/feishu/callback`。例如独立域名使用 `https://demands.example.com/api/auth/feishu/callback`;子路径部署使用 `https://example.com/demands/api/auth/feishu/callback`。管理员的「飞书集成」页面会展示实际地址。
3. 获取用户基础身份接口无需额外申请权限;发布应用版本并设置成员可用范围。应用仅请求基础登录信息,不请求邮箱、手机号、通讯录同步或长期离线访问。
4. 在服务器 `.env` 中设置 `FEISHU_APP_ID`、`FEISHU_APP_SECRET`。可选 `FEISHU_TENANT_KEY` 将授权限制到指定企业。
5. 更新代码、构建并重建容器。普通 Node 部署运行 `npm run build`,随后由进程管理器重新启动 `npm start`;Compose 部署运行 `docker compose up -d --build --force-recreate`。
配置 `LOGIN_CLIENT_IP_HEADER` 后,飞书授权入口与密码登录共用每来源 60 次/分钟的数据库限流;缺少或无效的可信 IP 会拒绝授权。未配置时不信任客户端自行提供的转发头;生产环境应按部署说明配置受信代理头。
应用采用与当前授权端点 PKCE 配套的 OAuth v2 token 接口、随机单次 state、HttpOnly 浏览器校验 cookie 和 PKCE S256。只使用服务端取得的 `app_id + tenant_key + open_id` 识别身份,不信任浏览器提供的身份,不按姓名或邮箱自动匹配。用户 access token 只用于当次读取身份,不落库。授权码兑换使用 v2 接口并保留完整的 S256 校验。后续迁移接口必须先验证真实用户的完整授权回调。
参考:[获取授权码](https://open.feishu.cn/document/authentication-management/access-token/obtain-oauth-code)、[获取 user_access_token](https://open.feishu.cn/document/authentication-management/access-token/get-user-access-token)、[获取用户信息](https://open.feishu.cn/document/server-docs/authentication-management/login-state-management/get)。
## 2. 首次登录自动注册与已有账号绑定
新成员直接点击登录页「飞书登录」并完成授权,系统自动创建普通成员账号、关联该飞书身份并进入工作台,无需管理员提前开通或先设置密码。账号使用飞书姓名显示、生成独立用户名;并发或重复登录复用同一个账号,不按姓名或邮箱自动合并,不自动授予管理员角色。自动注册受飞书应用可用范围及配置的 `FEISHU_TENANT_KEY` 限制。
已有绑定继续使用原账号、角色和需求。已有系统账号但尚未绑定的成员,应先使用账号密码登录,完成初始密码修改,再通过账号菜单「飞书绑定」关联自己的身份,以保留原有需求。若直接以新飞书身份登录,系统会创建独立账号。
飞书注册的账号初始不支持密码登录,也没有通用或默认密码。成员可在账号菜单「设置密码」中设置第一份系统密码,之后使用页面展示的账号及密码登录;首次设置须已登录,设置后撤销旧会话。已有密码的账号修改时仍需验证当前密码。
一个系统账号只能绑定一个飞书身份,同一身份只能关联一个系统账号。停用账号后,飞书登录仍被拒绝,不会重新注册绕过停用。管理员重置密码后仍须修改临时密码;绑定期间退出登录、重置密码或切换账号都会使该次绑定失效。
解绑前必须先有系统密码,并验证该密码。成功后撤销该账号所有会话并给当前浏览器换发会话,原账号和需求保留。解绑后的飞书身份再次直接登录会创建新账号;如需继续使用原账号,应先用密码登录原账号,再重新绑定飞书。
## 3. 配置群通知
1. 在目标飞书群添加「自定义机器人」,将完整 Webhook 配置为 `FEISHU_BOT_WEBHOOK`。
2. 建议开启签名校验,将签名密钥配置为 `FEISHU_BOT_SECRET`。如开启关键词校验,关键词设为「需有序」;IP 白名单应包含服务器实际出口 IP。
3. 重建容器使环境变量生效,在账号菜单 →「飞书集成」发送测试消息。
通知群里的所有成员都能看到正式需求的标题、状态、操作人、开发责任人和详情链接,因此应选用有权接收这些摘要的内部协作群。消息不包含需求正文、评审细节、附件、密码或身份 token。用户输入使用富文本消息中的纯文本节点发送,关闭实体解码;标题中的 at 标签不会触发提醒,详情地址使用独立链接节点。已有队列记录在实际发送时也应用此规则。点开详情仍需登录并校验系统权限。
自定义群机器人仅需 Webhook,不需要应用机器人、接收消息事件、事件订阅回调或消息发送 API 权限。它只推送通知;业务确认、验收等操作继续在系统内完成。
参考:[自定义机器人使用指南](https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot)。
## 4. 通知可靠性与运行方式
- 正式需求每次成功保存产生一条摘要,包括登记、修改、方案评审、排期、设计、开发进展、验收、变更、缺陷、发布、归档和取消。草稿及保存失败不产生通知。
- 消息与需求写入同一 SQLite 事务,按需求编号、保存版本和目标机器人去重。通知发送失败不会回滚已经保存的需求。
- Next.js Node 服务通过 instrumentation 启动后台队列,每 3 秒取一条。此实现适用于项目现有的持续运行 Node/Docker 部署,不适用于请求结束后进程即被冻结的无服务器环境。
- 失败按 30 秒、60 秒、120 秒、240 秒退避,最多自动尝试 5 次。发送中的任务租约为 60 秒,进程重启后可恢复;管理员可刷新状态并手动重试达到上限的通知。「通知筛选」可查看全部失败记录;全部通知与失败通知均支持每页 50 条的历史翻页,旧失败记录不会因新通知增加而失去重试入口。
- 这是至少一次发送:服务端已经发送但响应丢失时,重试可能产生重复消息。消息包含需求编号及保存版本以便辨识。
- 更换 Webhook 后,旧目标的未完成消息停止发送且不能转发至新群。关闭配置会暂停发送;恢复原 Webhook 后继续处理原目标积压。关闭期间的业务操作不追溯补发。
- 配置错误在管理员页面提示。机器人连接测试只会在点击测试按钮时发送,每 30 秒最多一次。
- 环境变量和密钥不返回前端;管理页只显示配置状态和经处理的错误。维护人员应定期备份 SQLite,绑定及队列包含在现有备份中。
## 上线验证
使用新飞书身份验证:首次登录 → 自动注册普通成员 → 直接进入工作台 → 再次登录复用账号。已有账号验证:密码登录 → 绑定 → 退出 → 飞书登录;尝试停用账号后飞书登录应失败。飞书注册用户可设置系统密码后解绑,继续用密码登录原账号。创建草稿应无消息;提交正式需求后应收到通知,消息链接应打开对应详情。切换到无权查看该需求的账号,链接不能泄露详情。
本地自动化使用隔离数据库和模拟飞书响应,不会向真实群发消息。真实飞书账号授权与群消息仍需配置凭证后验证。
首次启动会将数据库迁移到版本 3。上线前备份;回滚旧应用须同步恢复兼容的数据库备份。
+82 -18
View File
@@ -1,24 +1,88 @@
# 需有序 · 业务需求登记管理
# 需有序 · 自部署版本说明
基于本目录《开发SOP_公示版》及附件01–07制作,原文件保持不变。
本目录已从平台托管版迁移为独立 Next.js / Node.js 服务,不使用 ChatGPT 登录、平台身份请求头或 Cloudflare D1。SOP 正文及附件与站点 content/docs 中的副本同步维护,通过登录后接口下载。实施范围与功能说明、范围外事项由开发责任人在需求评审时提出方案并与业务方确认,业务登记和提交评审不再要求填写这两项;详情页「需求评审」提供开发账号指定、方案提交、退回及业务确认,既有内容保留。
## 已实现
- 我的工作台、需求列表、检索与优先级/项目筛选、待办、草稿。
- 四步登记表;草稿、基本登记和提交评审分别校验。
- 需求详情、版本冲突保护、同名需求提示/拦截。
- 业务验收清单和确认留痕;通过转待发布,不通过退回开发中。
- 已确认需求提出变更;保留原字段快照,等待开发评估及双方确认。
- 取消需求留痕、记录导出、原SOP和7个模板下载。
- 通过平台登录;按实际登录账号隔离D1持久化记录。
- 示例数据只用于页面体验,不会存入正式数据库。
## 登录与指定用户
## 当前使用边界
这是业务端首版。表单中的“需求负责人”是业务联系人,不表示已向该人员授权、指派系统任务或发送通知。跨部门成员权限、评审排期/开发提测/发布管理后台与企业账号集成尚未配置。实际登记后可维护信息并提交评审;后续阶段需要组织的开发协作系统接入,当前仅在明确标注的示例中体验。参考材料通过共享链接关联,目前未提供文件上传。
- 管理员通过「账号管理」开通业务用户或其他管理员,不开放公开注册。
- 使用本系统用户名与密码;用户名不区分大小写,可使用符合规则的邮箱作为用户名。
- 初始管理员由部署环境配置,仅在空数据库首次启动时创建,无默认密码。
- 初始密码、管理员重置的密码均要求用户登录后修改。
- 密码使用带随机盐的 scrypt 哈希;会话使用随机令牌,数据库仅保存令牌摘要。
- 账号停用、密码修改或重置会撤销相应会话;退出登录也在服务端撤销会话。
- 管理接口校验管理员角色,限制跨来源写入和重复登录尝试。
- 登录保留账号限流;可显式配置可信代理的客户端 IP 请求头,按来源隔离额度。管理员重置密码会清除目标账号锁定,保留来源限流。
- 用户管理自己登记的需求;指定开发责任人可查看相应正式需求并执行方案、排期、开发、提测、发布及归档操作。管理员可只读查看全部正式需求及当前、历史评审附件,但不能凭角色执行业务或开发操作;他人草稿及未保存附件仍私有。
## 数据与运行
React 19 + Vinext/Vite,Cloudflare Worker,D1数据库。`npm run dev` 为本地开发;`npm run build` 构建。数据库结构在 db/schema.ts,迁移在 drizzle/。托管绑定配置位于 `.openai/hosting.json`。所有API查询按登录账号过滤,更新使用revision乐观锁。
## 部署与数据
## 设计与验证
采用白色面板、冷灰工作区和蓝色主操作。设计参考为 ImageGen 的完整工作台,布局包含224px侧栏、概览条、待办提醒、列表与右侧指引。实现按该方向检查了侧栏/导航、标题与主按钮、指标条、提醒条、表格行与状态、右侧指引六处。原图将资料待补充表现为状态,系统按SOP改为“待评审”下的辅助标记;优先级标签采用“P2 普通”避免误解;其余文案随实际数据动态更新。
- Next.js standalone 输出,保留现有业务界面和需求操作。
- Node.js 24 或更高版本,使用内置 SQLite;Docker 基础镜像为 node:24-bookworm-slim。
- 账号、需求、附件内容及元数据、会话和登录限流记录存放在 DATA_DIR/demand-center.sqlite;数据库版本 2 自动新增附件表,兼容已有账号与需求。
- Docker 使用持久数据卷、非 root 用户、健康检查,默认端口仅绑定到宿主机 127.0.0.1。
- npm start 使用独立部署输出,并在进入构建目录前将数据路径解析为项目根目录下的绝对路径,避免构建清理影响业务数据。
- scripts/backup.mjs 提供在线一致性备份和完整性检查。
- 具体部署、HTTPS 反向代理、备份恢复步骤见 DEPLOYMENT.md。
验证记录:TypeScript 检查通过;完整构建通过;本地接口20项检查覆盖未登录、归属隔离、分阶段校验、持久化、去重、版本冲突、验收版本/清单/显式确认、通过与退回、变更快照。通过内置浏览器完成保存草稿→刷新→继续填写→正式登记、示例逐项验收、未保存关闭提示;检查1536×1024与390×844,无页面横向溢出,手机表格可独立横向滚动。WebMCP已验证搜索的有效/无效输入以及打开登记表;不会自动提交需求。测试数据仅写入本地库并已清理,生产库不预置测试数据。
## 已完成的验证
- TypeScript 检查及生产构建通过。
- 26 项单元测试通过,包括 11 项认证测试、3 项需求快照合并测试、5 项评审待办、个人范围与版本失效测试、5 项附件迁移、权限、限制、事务回滚和过期清理测试,以及 2 项文档登记与下载地址检查。
- 174 项 HTTP 集成检查通过(本次使用默认根路径);使用真实 standalone 生产入口与独立测试数据库。覆盖认证、账号管理、按需求授权、业务与开发权限隔离、旧记录保留、方案提交与退回、明确确认、旧版本及并发冲突拦截、业务修改后确认失效、更换责任人撤销访问,以及重启后版本与确认记录持久化;另覆盖附件上传下载、大小和来源限制、暂存恢复、越权拦截、需求保存绑定、旧客户端兼容、历史评审材料保留及备份中的文件内容验证。文档接口新增验证预览鉴权、正文一致性、全部 8 份 Word 的 OOXML 文件结构、类型与下载名称、未知文档及格式拦截。
- Docker Compose 配置检查通过。
- 直接运行版本在本机 Node.js 26 验证。
- 页面验证使用隔离的无界面浏览器(内置浏览器连接不可用):1440×1000 和 390×844 检查登录页、账号菜单、账号列表/搜索、新建账号弹窗、修改密码页,截图人工复核通过,无浏览器运行错误。
- 2026-09-17 使用两个独立浏览器会话完成真实界面回归:登记、指定开发账号、手机端填写方案、业务退回、开发重提、业务确认、历史记录查看和业务变更后重新评审;同时验证未保存输入保护、显式确认及开发端不显示业务操作。桌面 1440×1000、手机 390×844 截图复核通过,无浏览器运行错误。
- Review 修复另通过 6 组隔离浏览器回归:入口清理旧筛选、进行中/已完成预设、迟到加载保留新草稿与原记录、失败重试、未修改表单的关闭按钮。
- 附件浏览器回归通过多文件上传、桌面/手机布局、中文原文件名下载与字节核对、保存时移除、上传失败重试、空文件提示、刷新找回、放弃编辑清理;页面无运行错误。
- 附件恢复修复通过 `tests/attachments-recovery.browser.py` 的 6 组隔离浏览器回归:找回附件后取消/移除不删除原文件、原窗口继续保存、新上传文件仍可清理、加载失败保留表单并重试、暂存上限自动刷新并展开列表、自动刷新失败后手动重试;移动端错误提示及重试按钮复核通过。
- 在线备份验证包括 WAL 数据完整读回、0600 权限及拒绝覆盖已有备份,并确认备份包含完整附件字节。
- 模板交互通过 `tests/templates.browser.py` 的 6 组隔离浏览器回归:对应模板及关联跳转、Word 下载、关闭和 Escape 返回原表单、业务背景上传与文档链接跨步骤保存、模板目录与手机端宽表格、预览失败重试。桌面 1440×1000、手机 390×844 截图人工复核,无浏览器运行错误。
- 8 份 Word 文档由既有源文档生成,逐页渲染并复核共 29 页;修复中文字体、标题装饰线、验收和变更表格列宽及表格跨页拆行问题。生产构建校验源文档与 Word 的 SHA-256 摘要,避免模板版本错位。
- 模板审查修复通过 `tests/templates-resilience.browser.py` 的 4 组隔离浏览器回归:脚本加载连续失败后重试/关闭/重开并保留文字、链接及附件字节;正文响应前按 Escape 和迟到响应;重新打开后快速 Escape 与父表单退出保护;模板目录关闭后的焦点归还。原有 6 组模板流程回归、静态检查及生产构建继续通过,桌面和手机端错误提示排版复核通过。
## 模板使用改进
- 业务背景填写区增加上传文件、内置模板预览与 Word 下载;允许简短说明,并提供填写完成后的文档链接输入。
- 业务背景与参考材料两步复用同一附件列表和链接字段,保留既有恢复、移除及保存机制。
- 基本信息、业务背景、验收标准和数据来源展示对应内置模板;流程与规范集中展示 SOP 和 7 份模板。
- 用户提供的飞书链接已确认为模板总目录,统一按目录入口展示,并提示先创建副本;不将其标为某一份具体模板,也不自动修改飞书文档。
- 模板正文在系统内阅读,支持表格与相关模板跳转;Word 文件走现有登录鉴权接口,旧 Markdown 下载地址继续兼容。此次无需数据库迁移。
- 预览弹窗直接随页面加载,正文渲染模块按需加载并捕获失败;重新加载会重新请求失败的脚本,正文渲染错误也由局部错误边界承接,不卸载登记表。表单同步记录预览打开状态,避免弹窗初始化期间 Escape 误触发退出,关闭后将焦点归还入口按钮。
## 使用边界
当前源代码包含业务端、账号管理、方案评审及完整交付流程,操作职责和准入条件见 README.md。发布和回滚操作登记实际执行结果,不直接执行外部部署、数据库恢复或发送消息。内置演示数据及演示入口已移除,仅展示实际登记的记录。参考材料支持链接及文件附件,单文件 20 MB、每条需求最多 10 个;文件通过鉴权接口下载,随 SQLite 备份恢复。
## 管理员需求可见范围修复
- 增加管理员「全部需求」入口,展示所有正式需求,并同步开放当前及历史评审附件的只读下载。
- 列表和附件接口复用相同的读取条件,草稿与未保存附件仍仅本人可见;请求按当前账号角色鉴权。
- 写入接口保留登记账号及指定开发责任人的校验,管理员观察权限不授予编辑、取消、变更、指派、代提方案或代做业务确认。
- 「我的需求」、工作台计数和待办仅包含本人参与的需求;查看他人需求时显示只读提示。
- 新增接口回归覆盖全部写操作拦截、当前/历史附件、草稿转正式、明确指派与撤销、角色降级即时失效等;共 174 项通过。多账号浏览器 5 组回归及 1440、390、320 像素布局验证通过,26 项单元测试、静态检查与生产构建通过。无需数据库迁移。
## 完整交付流程
- 方案确认后的交付计划由开发提出、业务确认,包含工作量、优先级、提测/验收反馈/上线日期及设计要求。需要设计时,完成独立设计确认后再开发。
- 增加技术方案与依赖检查、开发进度、阻塞责任与跟进日期、协作记录;不跳过未确认计划、设计、阻塞和待处理变更。
- 开发提交测试环境、版本、测试数据说明、自测、代码审查、集成证据和可编辑验收清单。业务逐项确认指定文档版本与测试轮次;不通过返回开发,超时不会自动通过。
- 增加变更提出/撤回、开发影响评估和业务同意/拒绝。批准后同步范围、验收标准、文档版本及计划,并重新开发验收;拒绝保留原范围。新旧材料及确认均保留。
- 增加缺陷登记、修复、独立复验与一般问题遗留申请。阻断缺陷必须复验关闭;一般遗留须业务确认计划。修复已交付版本会撤回旧提测状态,避免发布不含修复的旧版本。
- 发布始终由当前开发责任人承担。发布前检查、验收版本匹配、备份/回滚/通知记录、生产验证、15 分钟至 7 天观察窗口以及交接/监控归档均有服务端条件检查。
- 已上线或归档记录支持故障启动修复、实际回滚记录及复盘。涉及数据恢复前需业务明确批准目标版本和增量保留方案;在后续开发阶段仍能恢复上一线上版本。代码回滚不会擅自清除其他业务阻塞。
- 允许业务方在交付期间更换开发账号,要求先处理待确认变更;旧方案与验收失效,新开发重新确认方案和计划,旧开发权限立即撤销。取消需求同步结束待确认变更及阻塞,过程历史保留。
- 新增「交付流程」「缺陷」栏目,完善「需求变更」与历史逐项验收展示;页面按职责展示操作,保存后保留所在栏目,失败保留输入,离开前保护未保存内容。工作台提供按职责分配的待办与逾期提示。
- 所有写入继续校验身份、业务/开发职责、状态、版本及数据库修订号;管理员只读权限不扩大。数据追加在需求 JSON 记录内,兼容历史需求,无需改变 SQLite 表结构;备份与恢复包含新记录。
- 本次静态检查、TypeScript、生产构建及 34 项单元测试通过;原有 174 项接口回归、新增 102 项完整流程接口检查通过,覆盖多角色、并发冲突、退回、缺陷失效、时间门槛、恢复审批、交接、取消及重启持久化。
- 新增 5 组完整流程页面回归通过:排期/设计/开发、手机提测/业务验收、发布验证/观察归档、变更/缺陷闭环、管理员只读;另有原模板容错 4 组和管理员权限 5 组浏览器回归通过。桌面及 390 像素手机截图已复核,无页面运行错误。
## 完整交付流程审查修复
- 新发布前拦截所有未结束的数据恢复申请,开发可记录原因撤回,业务方可确认或退回。恢复操作和确认关联发布记录;旧版本遗留申请保留入口,但已被替代的申请不能再批准,只可撤回/退回后重新申请。
- 设计确认待办覆盖已排期及开发中,校验当前方案版本;变更后旧设计不会再错误提示“开始开发”。历史设计明确标识,开发准入与提测继续使用相同确认条件。
- 验收清单按现有编号集合生成未使用编号,删除中间项、手动调整编号后再添加不会产生系统生成的重复编号。
- 新增受约束的紧急发布入口:仅当前开发责任人、已有线上故障、与原发布一致的方案和文档、业务规则/范围不变且无不可逆数据处理时可使用。自测、审查、构建回归、已知风险、备份恢复、通知和观察检查仍必填;未修复的阻断缺陷会拦截。其他情况继续常规评审验收。
- 紧急发布保留实际版本及技术证据,撤回旧提测但不伪造验收通过记录;业务方收到关联发布版本及截止日期的补充验证待办,历史未补验记录也可处理。当前版本不通过返回修复;通过后仍须生产验证、观察、交接和缺陷处理完成才能归档。进度条使用“业务补验”,补验前不标记通过。
- 单元测试 40 项、完整交付 HTTP 检查 123 项、原有接口回归 174 项通过;新增 4 组真实页面回归覆盖设计待办、清单增删、恢复撤回、手机紧急发布及业务补验归档,并检查管理员没有新增写入入口。桌面和手机截图复核通过。
- 数据仍使用既有 SQLite 需求记录,无新表迁移;现有备份与恢复包含新增记录。
+100 -82
View File
@@ -1,126 +1,144 @@
# vinext-starter
# 需有序 · 需求登记管理系统
A clean full-stack starter running on [vinext](https://github.com/cloudflare/vinext), with optional Cloudflare D1 and Drizzle support.
面向业务与开发的需求协作系统,可部署在自己的服务器,支持本系统账号密码及飞书登录,不需要 ChatGPT 或 OpenAI 账号。
## Prerequisites
- 管理员可创建、停用账号和重置密码;新成员首次通过飞书授权登录会自动注册普通成员账号。
- 业务用户登记需求、确认方案与排期、验收版本、审批变更和复验缺陷;开发责任人完成方案、开发、提测、发布、生产验证与归档。
- SOP 和 7 份配套模板支持系统内预览及 Word 下载,也可打开飞书模板总目录创建副本。
- 账号、会话和需求保存在服务器的 SQLite 数据库,重启或更新应用不会清空数据。
- Node.js `>=22.13.0`
- Portable: Windows, macOS, or Linux; no Bash required
- Managed Linux: managed Linux runtime with Bash, `flock`, `curl`, `sha256sum`, and GNU `timeout`
- Git is required only for publishing
需求登记账号管理业务信息并代表业务方确认方案;开发负责人默认由系统管理员担任,无需手动填写账号,负责从方案到发布的完整交付。管理员可只读查看全部正式需求及其附件,草稿与未保存附件仍仅本人可见;普通用户只可查看自己登记或被指定负责开发的需求。当前源代码已补齐排期、设计确认、开发、提测、验收、发布和归档,以及变更、缺陷、回滚与复盘。
## Sites Lifecycle
## 管理员查看需求
The Sites initializer copies the shared starter and selects managed-linux only when `SITES_MANAGED_LINUX_CONTAINER=1`; otherwise it selects portable. It saves the selection only in ignored `.sites-runtime/execution-profile.json`. Both profiles copy/configure first, then use the plugin's separate `install-dependencies.mjs` step to measure installation independently. Edit source under `app/` and follow the Sites skill for installation, preview, builds, and publishing.
管理员通过侧栏「全部需求」查看所有正式需求,可搜索、筛选、查看详情及评审历史,并下载当前和历史评审附件。其他人的草稿与未保存附件不会出现在列表或下载接口中。「我的需求」、工作台统计与待办仅包含本人登记或负责开发的需求。
Whenever reopening or moving a checkout, run `node <plugin-root>/scripts/configure-execution-profile.mjs` before project commands. Profile changes do not alter tracked source or require reinstalling otherwise-valid dependencies; restart an existing preview to use the new selection. Do not commit or upload `.sites-runtime/`.
只因管理员身份获得的查看权限不包含编辑、取消、变更、指定开发、提交方案或业务确认。管理员自己登记的需求保留业务权限;自动或已有分配为开发负责人时,可按开发职责完成方案与交付。更换责任人后,对应操作权限随之撤销。
This starter does not use `wrangler.jsonc`.
## 需求评审
`install:ci` runs `npm ci` once against the shared lockfile, disables parent-workspace discovery, and includes required dev/optional dependencies despite production/omit settings. Sharp defaults to prebuilt binaries unless explicitly configured otherwise. Do not overlap installers.
1. 业务方补齐验收标准等材料并提交评审,打开需求详情的「需求评审」。
2. 系统自动带出开发负责人,无需填写或指定账号。新正式需求、草稿转正式需求及未分配的进行中旧需求默认使用最早创建且启用的管理员账号;已有具名分工保留。旧需求读取时解析默认负责人,在下一次成功保存时持久化;不改写历史方案或确认记录。管理员自己登记的需求也可以完成开发步骤。
3. 开发责任人登录后点击「刷新需求」,打开分配给自己的需求,填写实施范围与功能说明、范围外事项并提交。
4. 业务方刷新需求,核对方案后勾选确认,或填写修改意见退回。开发责任人修改后提交新版本。
- **Portable:** Preserve host HOME, npm cache, registry, proxy, temporary paths, retry/concurrency settings, and lifecycle-script policy. Use `--prefer-offline --no-audit --no-fund`.
- **Managed Linux:** Use the existing project-local HOME/cache/tmp setup and Linux install lock, tarball preflight, and timeout. Restore the image-seeded npm cache only when its lockfile hash matches; retain network fallback. Builds keep their existing timeout. These helpers are not invoked by the portable profile.
系统自动记录方案版本、开发提交人、业务确认人及时间。修改业务需求、更换开发责任人或要求调整已确认方案,会使当前方案失效并要求重新提交确认,旧方案及确认记录保留。更换开发责任人后,原开发账号失去方案提交权限;普通账号同时失去查看权限,管理员仍保留全局只读权限。待办按当前账号的业务或开发职责显示。
`scripts/sites-env.mjs` preserves the caller's HOME, npm cache, proxy, XDG, and temporary-directory configuration while defaulting Wrangler and Miniflare state to the checkout. If npm reports an unwritable cache, select a writable path with `npm_config_cache` for that install. The `dev` and `start` scripts also keep Wrangler logs inside the checkout. Generated `.sites-runtime/` and `.wrangler/` directories are disposable and ignored by Git.
已有记录的方案内容保留为历史内容,不会被自动认定为已确认。业务账号在普通信息编辑中不能修改方案。
On portable, `npm run dev` uses `vinext dev` with HMR, starting at port 5173. Vinext records the running server in ignored `.vinext/` state, rejects an ordinary duplicate launch, and recovers stale state after a stopped process; exactly simultaneous starts can race. Pass `--port <port>` or `--hostname <host>` after `npm run dev --` when needed; keep portable previews on loopback.
开发账号停用或不可用后,启用的管理员可从「全部需求」打开记录,在「需求评审」确认「接手开发职责」,无需填写开发账号。接手只分配给当前管理员,记录原负责人、新负责人和时间,保留历史方案、计划、验收与附件,并回到待评审重新确认方案和排期;原提测版本撤回,后续需重新提测验收。已有待确认变更时,先由业务方处理或撤回;材料尚未齐备的需求可先交接,再由业务方补齐材料。草稿和已取消需求不提供接手入口,启用中的负责人不会被接管。
On managed Linux, use `sites-preview start` only for requested browser QA. The project's dev script runs Vite and accepts the supervisor's `--host 0.0.0.0 --port 4173 --strictPort` arguments. The internal browser uses `http://terminal.local:4173/`; it is not a user-facing URL. The supervisor owns the preview lifecycle. The ignored local profile survives the supervisor's cleared process environment.
同一管理员兼任业务和开发角色时,任一职责对应的阻塞事项都会进入「待我处理」。
The portable profile simulates ChatGPT sign-in only for loopback development requests. Visit `/signin-with-chatgpt?return_to=/` to sign in as `local_seedy` (`seedy@sites.test`, display name `Seedy`) and `/signout-with-chatgpt?return_to=/` to sign out. The development cookie preserves that identity across server restarts. Mock auth is disabled in the managed-linux profile and is not included in production builds; hosted authentication remains dispatch-owned.
## 完整交付流程
The Worker uses `vinext/server/fetch-handler`, including Vinext's config-aware image handling. After building, `npm start` runs that Worker locally through Wrangler on `127.0.0.1`, sharing `.wrangler/state` with dev preview and local D1 migrations; it does not deploy the site or simulate sign-in. Use the URL printed by the server. Pass `npm start -- --port <port>` to select a different built-preview port.
| 阶段 | 开发责任人 | 业务方(登记账号) |
| --- | --- | --- |
| 方案评审 | 提出实施范围、范围外事项 | 确认或退回方案 |
| 排期与设计 | 提出工作量、日期、优先级;按需提交设计 | 确认排期,确认或退回设计 |
| 开发 | 记录技术方案和依赖,开始开发、更新进度 | 提供业务支持、处理约定阻塞 |
| 提测与验收 | 提交测试版本、环境、自测、代码审查、集成记录和逐项清单 | 对指定文档、测试版本逐项验收并明确确认 |
| 发布与归档 | 完成实际部署,登记发布;生产验证、观察、交接并归档 | 验收通过即按约定计划同意发布,跟进遗留事项 |
| 紧急故障修复 | 在已发布的同一方案范围内,经技术验证后登记紧急发布 | 发布后按指定版本补充业务验证,完成前不能归档 |
| 变更 | 评估范围、验收口径、工作量和排期影响 | 发起、撤回、同意或拒绝变更 |
| 缺陷与恢复 | 修复、提交复验;登记实际回滚结果及复盘 | 复验关闭缺陷,确认一般问题遗留计划;事先批准数据恢复方案 |
Local previews use Miniflare's placeholder `Request.cf` metadata without a network lookup. Set `CLOUDFLARE_CF_FETCH_ENABLED=true` to opt into fetching preview metadata; this setting does not change hosted request metadata.
在需求详情的「交付流程」「业务验收」「缺陷」「需求变更」中操作;「进度记录」保留人员、时间、版本及处理结论。协作方操作后,关闭详情并点击「刷新需求」查看最新数据,待办与超期提示按账号职责显示。
Local tool usage metrics are disabled by default. Set `WRANGLER_SEND_METRICS=true` to opt in.
- 发布始终由当前开发责任人负责,不单独设置发布账号;管理员的全局查看权限仍为只读。
- 未确认方案、排期或必要设计,不能跳过开发准入;阻塞与待确认变更会暂停后续交付。业务验收超时不会自动通过。
- 修复或撤回已提测版本、批准范围变更、更换开发责任人后,常规交付必须重新提测验收,旧版本与证据保留。符合下述条件的线上故障可走紧急发布。
- 阻断缺陷必须修复并由业务方复验;一般问题须经业务方确认遗留计划后,才可带入发布和归档。
- 常规发布版本必须与已验收版本一致。生产验证通过且约定观察期(15 分钟至 7 天)结束,完成通知、交接和监控记录后才能归档。
- 已上线或归档后出现故障,开发可启动修复;涉及数据恢复时,业务方先确认目标版本、数据影响和增量保留方案。进行新一轮开发时仍可登记原线上版本的恢复,重复回滚被拦截。
- 更换开发责任人需先处理待确认变更,随后重新评审和排期;旧开发账号随即失去写入权限,普通账号也失去读取权限。
- 所有操作保存前校验角色、状态、版本和并发修订号;失败保留表单内容。完整交付信息仍保存在需求的 SQLite 记录中,现有备份与恢复机制覆盖这些数据。
## Included Shape
紧急发布入口位于「交付流程」:先登记线上故障并启动修复,再由当前开发责任人选择「登记紧急生产发布」。入口只适用于已有发布记录、当前方案及文档与该版本一致、业务规则和范围不变、且不涉及不可逆数据处理的修复。历史发布缺少方案版本时,应走常规评审验收。涉及规则、范围或不可逆数据变化时,仍须先完成业务确认和常规验收。
- edit site code under `app/`
- `app/chatgpt-auth.ts` provides optional dispatch-owned ChatGPT sign-in helpers
- `.openai/hosting.json` declares optional Sites D1 and R2 bindings
- `vite.config.ts` simulates declared bindings for local development
- `db/index.ts` reads the D1 binding from the Cloudflare Worker environment
- `db/schema.ts` starts intentionally empty
- `@cloudflare/workers-types` provides Worker types; `cloudflare-env.d.ts` declares optional `DB`/`BUCKET` bindings—update these declarations if binding names change
- `examples/d1/` contains an optional D1 example surface
- `drizzle.config.ts` supports local migration generation when needed
紧急发布需要原因、修复影响、自测、代码审查、构建与关联回归证据,以及备份、恢复、通知和观察检查;未修复的阻断缺陷仍会拦截。开发同时填写主分支同步、下一工作日记录补充和后续业务验证安排。业务方在待办中按实际发布版本补充验证,当前版本不通过会返回修复;通过后仍需生产验证、观察、交接及缺陷关闭或遗留确认才能归档。紧急发布不会补写或伪造常规验收通过记录。
## Workspace Auth Headers
新发布前须处理所有未结束的数据恢复申请,开发可明确撤回申请,或由业务方确认/退回。历史遗留的旧版本申请仍有入口:已被新发布替代的申请只能撤回或退回,再针对当前版本重新申请;批准不能跨版本复用。
Signed-in visitors receive both `oai-authenticated-user-id` and `oai-authenticated-user-email`. Private Sites require every visitor to sign in; public Sites may also have anonymous visitors, for whom neither header is present.
设计待办覆盖已排期和开发中,并按当前方案版本校验;旧设计确认不能使新方案跳过设计。验收清单增删后自动选择尚未使用的编号,保留其他验收项的编号和内容。
The user ID is stable for the same user on the same Site and different across Sites. Use it as the durable user key; use email and name for display or contact purposes.
本系统负责流程审批、证据与结果记录。实际代码构建、部署、数据库恢复和业务通知由开发责任人在对应系统执行,再在这里登记;站内待办及可选的飞书群通知已实现;CI/CD 执行器尚未接入。
SIWC-authenticated workspace sites may also receive `oai-authenticated-user-full-name` when the user's SIWC profile has a non-empty `name` claim. The full-name value is percent-encoded UTF-8 and is accompanied by `oai-authenticated-user-full-name-encoding: percent-encoded-utf-8`.
## 参考附件
Treat the full name as optional and fall back to email when it is absent:
可在「业务背景与目标」的说明框旁点击「上传文件」,或在「数据与参考材料」中点击「上传附件」。两个入口共用同一份附件列表,可一次选择多个文件,每个文件不超过 20 MB,每条需求最多 10 个。保存草稿、登记需求或提交评审时,附件随需求一起保存;原有参考链接仍可使用。
```tsx
import { headers } from "next/headers";
业务背景可简短说明,详细材料可上传文件或填写已完成的飞书文档链接,也可以两者同时使用。业务背景步骤的文档链接与最后一步的参考材料共用同一内容,切换步骤不会丢失。
export default async function Home() {
const requestHeaders = await headers();
const userId = requestHeaders.get("oai-authenticated-user-id");
const email = requestHeaders.get("oai-authenticated-user-email");
const encodedFullName = requestHeaders.get("oai-authenticated-user-full-name");
const fullName =
encodedFullName &&
requestHeaders.get("oai-authenticated-user-full-name-encoding") ===
"percent-encoded-utf-8"
? decodeURIComponent(encodedFullName)
: null;
需求详情及需求评审中可下载附件,权限与需求一致:正式需求由登记账号、当前指定的开发责任人和管理员访问;草稿与未保存附件仅本人可见。更换责任人后,原开发账号失去访问权限。
const displayName = fullName ?? email;
// ...
}
```
本窗口新上传且未保存的附件会在移除或取消编辑时清理;找回的附件仅取消本次选用,不会自动删除原文件。刷新后可在「找回未保存的附件」中重新选用,临时文件保留 24 小时。修改当前附件后需保存,已有方案确认会失效并要求重新评审。历史评审引用的附件保留供核对,未被历史版本引用的移除文件会清理。
## Optional Dispatch-Owned ChatGPT Sign-In
未保存附件列表加载失败时,可直接点击「重新加载未保存附件」,无需关闭表单。达到暂存上限时会自动刷新并展开列表,可先选用或核对后清理文件;自动刷新失败后仍可重试。
Import the ready-to-use helpers from `app/chatgpt-auth.ts` when the site needs optional or required ChatGPT sign-in:
文件与业务记录一同保存在 SQLite 中,重启、应用更新及现有备份恢复均包含附件。首次启动新版本会自动升级数据库结构;更新反向代理时请同步允许至少 22 MB 的上传请求。
- Use `getChatGPTUser()` for optional signed-in UI.
- Use the returned `userId` as the stable user key for user-owned records; do not use email as a durable identifier.
- Use `requireChatGPTUser(returnTo)` for server-rendered pages that should send anonymous visitors through Sign in with ChatGPT.
- In a Server Component, start sign-in with `<a href={chatGPTSignInPath(returnTo)} target="_top">`. The auth helper module is server-only; do not import it into a Client Component.
- Do not use `fetch`, XHR, a client-side router, or a framework link that can prefetch the sign-in route. SIWC must start as a top-level navigation.
- Never request the AuthAPI authorization endpoint directly. The dispatch-owned `/signin-with-chatgpt` route must start the SIWC flow.
- Use `chatGPTSignOutPath(returnTo)` for browser sign-out links or actions.
- Pass a same-origin relative `returnTo` path for the destination after sign-in or sign-out. The helper validates and safely encodes it.
- Mark protected pages with `export const dynamic = "force-dynamic"` because they depend on per-request identity headers.
## 模板预览与下载
Dispatch owns `/signin-with-chatgpt`, `/signout-with-chatgpt`, `/callback`, the OAuth cookies, and identity header injection. Do not implement app routes for those reserved paths. Routes that do not import and call the helper remain anonymous-compatible.
基本信息、业务背景、验收标准和数据来源填写区提供对应模板入口。「查看模板」直接在系统中显示正文,支持表格、相关模板跳转及返回;关闭预览后继续填写原表单。「下载模板」提供可用 Word 或 WPS 编辑的 `.docx` 文件。
SIWC establishes identity only; it does not prove workspace membership. Use the Sites hosting platform's access policy controls for workspace-wide restrictions, or enforce explicit server-side membership or allowlist checks.
模板预览加载失败时,可在弹窗内重新加载,或者返回继续填写;已填内容、文档链接和附件会保留。预览打开时按 Escape 只关闭预览,焦点返回原入口。
Use SIWC for account pages, user-specific dashboards, saved records, and write actions tied to the current ChatGPT user. Leave public content anonymous.
飞书入口统一指向用户提供的[模板总目录](https://ecnldnvsv8es.feishu.cn/wiki/Bvnbw852biK7qRkhwJkcOIvun4f?from=from_copylink),可在目录内选择模板并创建副本,填写后把文档链接放回需求。「流程与规范」集中提供 SOP 和全部 7 份配套模板。
## Local D1 migrations
模板预览和下载均要求登录且已修改初始密码。源文档位于 `content/docs`,Word 文件位于 `content/word`。修改源文档后,使用具备 `python-docx` 的 Python 环境运行 `scripts/build-word-templates.py`,再渲染检查输出排版。`npm run verify:templates` 检查源文档和 Word 文件的摘要是否一致,生产构建也会执行此检查;服务器运行和构建不需要 Python。
For a D1-backed local preview, generate SQL with `npm run db:generate`. Build once through the Sites skill's build entrypoint (or `npm run build` for standalone use) to generate `dist/server/wrangler.json`, rebuilding if bindings change. From the project root, apply each pending migration in order:
## 自己服务器部署
推荐使用 Docker Compose。需要 Docker Engine 和 Compose 插件,以及反向代理提供的 HTTPS 域名。
```sh
node --import ./scripts/sites-env.mjs ./node_modules/wrangler/bin/wrangler.js d1 execute DB --local --config dist/server/wrangler.json --persist-to .wrangler/state --file drizzle/0000_example.sql
cp .env.example .env
chmod 600 .env
```
Replace the filename with the pending migration and `DB` with your D1 binding name if different. Use `.wrangler/state`, not `.wrangler/state/v3`; Wrangler adds the versioned directories. Do not replay migrations already applied locally. This updates only the preview database; publishing applies production migrations separately.
编辑 `.env`,填写 `APP_URL`、初始管理员用户名和至少 12 位的强密码,再启动:
## Diagnostic Commands
```sh
docker compose up -d --build
docker compose ps
```
- `npm run install:ci`: perform the one locked dependency install
- `npm run dev`: start the Vite/Vinext development server
- `npm run build`: build the deployable Sites artifact
- `npm run start`: preview the built Worker locally with D1/R2 support
- `npm run db:generate`: generate Drizzle migrations after schema changes
容器默认只绑定服务器的 `127.0.0.1:3000`。将反向代理指向此地址,使用 `APP_URL` 配置的域名打开系统。用初始管理员账号登录后,按提示修改初始密码,再创建业务用户。
When using the Sites plugin, follow its skill instructions for installation, builds, and publishing. These npm commands remain available for standalone use.
完整的 Nginx 配置、账号初始化、备份恢复和更新步骤见 [部署说明](DEPLOYMENT.md)。
The portable build runs Vinext directly without a host `timeout` command. The managed-linux build uses `scripts/build-verified.sh` and its existing `SITES_BUILD_TIMEOUT` setting.
## 本地运行
## Learn More
需要 Node.js 24 和 npm。
- [vinext Documentation](https://github.com/cloudflare/vinext)
- [Drizzle D1 Guide](https://orm.drizzle.team/docs/get-started/d1-new)
```sh
npm ci
cp .env.example .env.local
```
编辑 `.env.local`:将 `APP_URL` 设为 `http://localhost:3000`,填写管理员用户名和密码。
```sh
npm run dev
```
打开 `http://localhost:3000`。如使用不同主机名或端口,需要同步修改 `APP_URL`。
```sh
npm run typecheck
npm test
npm run build
npm run test:integration
npm run test:workflow
```
技术栈为 Next.js、React、Node.js 24 内置 SQLite;默认数据目录为 `./data`。Docker 使用持久化数据卷并以非 root 用户运行。在线一致性备份可执行 `npm run backup`,详见部署说明。
## 飞书登录与群通知
新增账号菜单入口「飞书绑定」,管理员另有「飞书集成」。在服务器配置飞书应用和群机器人后即可启用。新成员首次通过飞书授权后自动注册普通成员账号并进入工作台,无需预先开通或设置密码;重复登录复用账号。已有系统账号应先登录并绑定飞书以保留原有需求,不会按姓名或邮箱自动合并。飞书注册成员可选设置系统密码,解绑前需验证密码。
正式需求每次成功保存后推送流转摘要,草稿不通知。通知与需求一同持久化,后台每 3 秒处理一条,失败最多自动尝试 5 次;管理员可筛选失败通知、翻页查看全部历史记录(每页最多 50 条)、发送测试消息和重试失败通知。消息链接直接打开有权访问的需求详情。
配置步骤、权限、重试语义和上线检查见 [FEISHU.md](FEISHU.md)。
+22
View File
@@ -0,0 +1,22 @@
.account-page{min-height:100dvh;max-width:none;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;background:var(--bg)}
.account-brand{padding:0;margin-bottom:32px;gap:12px}.account-brand strong{font-size:26px}.account-brand span{color:#657793;font-size:12px}
.account-card{width:100%;max-width:438px;padding:36px;border:1px solid var(--border);border-radius:12px;background:#fff;box-shadow:0 6px 24px #10224705}
.account-card h1{font-size:25px;font-weight:650;letter-spacing:-.3px}.account-intro{font-size:14px;color:#657793;margin:9px 0 27px;line-height:1.8}.account-intro strong{font-weight:500;overflow-wrap:anywhere}
.account-form fieldset{padding:0;margin:0;border:0;min-width:0}.account-form .error-banner{margin-bottom:20px;overflow-wrap:anywhere}.account-field{display:flex;flex-direction:column;gap:8px;font-size:14px;font-weight:550;margin:0 0 19px}
.account-field input,.account-field select,.account-password-input input{min-width:0;width:100%;min-height:45px;border:1px solid #d5dfed;border-radius:6px;padding:10px 12px;background:#fff;color:var(--ink);font-weight:400;caret-color:var(--blue)}
.account-field input::placeholder,.account-password-input input::placeholder{color:#77869d;opacity:1}.account-field small,.account-field-hint{font-size:12px;line-height:1.7;font-weight:400;color:#64748b}.account-field small{margin-top:-1px}
.account-field:has(+.account-password-input){margin-bottom:8px}.account-password-input{position:relative}.account-password-input input{padding-right:48px}.account-password-input button{position:absolute;right:1px;top:1px;min-width:43px;min-height:43px;display:grid;place-items:center;border:0;border-radius:5px;background:none;color:#617593}.account-password-input button:hover{color:var(--blue);background:#f1f6ff}.account-password-input button:focus-visible{outline-offset:0}
.account-submit.btn{width:100%;min-height:45px;margin-top:26px}.account-help{text-align:center;color:#64748b;font-size:12px;line-height:1.8;margin-top:21px}.account-page-note{font-size:12px;color:#657793;line-height:1.8;margin-top:25px;text-align:center}.account-password-card{max-width:464px}.account-password-card .account-intro{margin-bottom:23px}.account-password-notice{margin-bottom:24px;color:#42618e}.account-show-password{font-size:12px;min-height:30px}.account-password-card .account-submit{margin-top:18px}.account-form-footer{display:flex;justify-content:space-between;gap:15px;padding-top:24px;margin-top:24px;border-top:1px solid var(--border)}.account-form-footer>button:last-child{margin-left:auto}.account-form-footer .text-button{font-size:13px;min-height:30px;text-decoration:none}
.account-spinner{animation:account-spin 1s linear infinite}@keyframes account-spin{to{transform:rotate(360deg)}}
.account-admin-page{min-height:100dvh}.account-admin-header{height:72px;background:#fff;border-bottom:1px solid var(--border);padding:0 max(32px,calc((100% - 1200px)/2));display:flex;justify-content:space-between;align-items:center;gap:25px}.account-back-link{display:inline-flex;align-items:center;gap:9px;text-decoration:none;font-size:14px;color:#526a8c;min-height:40px}.account-back-link:hover{color:var(--blue)}.account-admin-brand{display:flex;align-items:center;gap:9px}.account-admin-brand .brand-mark{height:23px;width:23px;gap:2px}.account-admin-brand .brand-mark i{border-radius:3px}.account-admin-brand strong{font-size:19px;letter-spacing:1px}.account-admin-main{max-width:1264px;padding:36px 32px 40px}.account-admin-main .page-heading{margin-bottom:25px}.account-admin-main .page-heading p{color:#657793}.account-admin-note{margin-bottom:25px;align-items:center;color:#42618e}.account-admin-note svg{margin:0}.account-success{display:flex;gap:9px;align-items:center;margin-bottom:20px;padding:11px 13px 11px 16px;color:#247b50;border:1px solid #cde5d5;border-radius:7px;background:#eef8f1;font-size:13px}.account-success .account-icon-button{margin-left:auto;min-width:30px;min-height:30px;color:inherit}.account-admin-main>.error-banner .text-button{margin-left:auto;color:inherit}
.account-users-panel{overflow:hidden}.account-users-toolbar{display:flex;justify-content:space-between;align-items:center;gap:24px;padding:22px 24px}.account-users-title{display:flex;align-items:center;gap:9px}.account-users-title>svg{color:#5375a4}.account-users-title h2{font-size:17px;white-space:nowrap}.account-users-title>span{color:#64748b;margin-left:1px;font-variant-numeric:tabular-nums}.account-users-tools{display:flex;align-items:center;gap:10px}.account-users-tools .search-field{width:260px;flex:initial}.account-users-tools input{font-size:13px}.account-users-tools input::placeholder{color:#73829a}.account-icon-button{min-width:38px;min-height:38px;border:0;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;background:none;color:#607798}.account-icon-button:hover{color:var(--blue);background:#f0f5ff}
.account-users-table-wrap{overflow-x:auto;padding:0 12px}.account-users-table{min-width:750px}.account-users-table th{padding:11px 14px;color:#5c6e88;font-size:13px}.account-users-table td{padding:18px 14px;font-size:13px}.account-users-table td:first-child{width:30%}.account-users-table td:last-child{min-width:170px}.account-user-identity{display:flex;align-items:center;gap:12px;min-width:0}.account-user-identity .avatar{height:35px;width:35px;flex-shrink:0}.account-user-identity>div{min-width:0;max-width:270px}.account-user-identity strong{font-size:14px;font-weight:550;display:block;overflow-wrap:anywhere}.account-user-identity>div>span{display:block;color:#687b96;font-size:12px;margin-top:2px;overflow-wrap:anywhere}.account-self{margin-left:7px;background:#eef3fb;color:#5d789f;border-radius:3px;padding:1px 5px;font-size:10px;font-weight:400}.account-role-admin{color:#325fad}.account-password-pending{display:block;font-size:11px;color:#7c6943;margin-top:5px}.account-login-date{font-variant-numeric:tabular-nums;white-space:nowrap;color:#64748b}.account-row-actions{display:flex;align-items:center;gap:20px}.account-row-actions .text-button{font-size:13px;min-height:34px;gap:7px;text-decoration:none}.account-list-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:65px 25px;text-align:center;color:#687b96}.account-list-empty svg{color:#7e9bc5}.account-list-empty h3{color:#435d82;font-weight:500}.account-list-empty p{font-size:13px}.account-users-footer{display:flex;justify-content:space-between;gap:20px;font-size:12px;color:#687b96;padding:16px 25px;border-top:1px solid var(--border)}
.account-dialog{display:block!important;max-width:460px!important;width:calc(100vw - 36px)!important;padding:25px!important;background:#fff!important;border:1px solid var(--border)!important;border-radius:10px!important;box-shadow:0 18px 55px #10224726!important;max-height:calc(100dvh - 40px);overflow-y:auto;color:var(--ink)}.account-dialog-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:8px}.account-dialog-heading [data-slot=dialog-title]{font-size:21px;font-weight:650;line-height:1.5}.account-dialog-heading>.account-icon-button{margin:-7px -8px -7px 0}.account-dialog-description{color:#657793!important;font-size:13px!important;line-height:1.8!important;margin-bottom:23px!important;overflow-wrap:anywhere}.account-dialog .account-field{margin-bottom:17px}.account-dialog .account-field:has(+.account-password-input){margin-bottom:8px}.account-field-hint{display:block;margin-top:8px}.account-dialog-actions{display:flex;gap:10px;justify-content:flex-end;border-top:1px solid var(--border);padding-top:21px;margin-top:25px}.account-dialog .btn{min-width:82px}
.account-page ::selection,.account-admin-page ::selection,.account-dialog ::selection{background:#dbe8ff;color:#102247}.account-page a,.account-admin-page a{text-underline-offset:3px}
@media(max-width:720px){.account-page{padding:32px 20px;justify-content:flex-start}.account-brand{margin:14px 0 28px}.account-card{padding:27px 24px}.account-card h1{font-size:24px}.account-intro{font-size:13px;margin-bottom:24px}.account-field input,.account-field select,.account-password-input input{font-size:16px}.account-page-note{max-width:280px}.account-admin-header{height:61px;padding:0 20px}.account-admin-brand strong{font-size:17px}.account-admin-brand .brand-mark{height:20px;width:20px}.account-back-link{font-size:13px}.account-admin-main{padding:25px 16px 35px}.account-admin-main .page-heading{align-items:flex-start;gap:14px}.account-admin-main h1{font-size:26px}.account-admin-main .page-heading p{font-size:12px;max-width:200px;line-height:1.8}.account-admin-main .page-heading .btn{font-size:12px;padding:8px 10px;min-height:39px;margin-top:3px;gap:5px}.account-admin-note{font-size:12px;align-items:flex-start;padding:12px}.account-admin-note svg{margin-top:2px}.account-users-toolbar{padding:17px 15px;gap:15px;flex-direction:column;align-items:stretch}.account-users-tools{gap:7px}.account-users-tools .search-field{width:auto;flex:1}.account-users-tools input{font-size:16px}.account-users-table-wrap{padding:0 8px}.account-users-table{min-width:705px}.account-users-table th{padding:10px 12px}.account-users-table td{padding:16px 12px}.account-users-table td:first-child{width:27%}.account-user-identity>div{max-width:185px}.account-users-footer{padding:15px;flex-direction:column;gap:3px}.account-users-footer>span{font-size:11px}.account-success{align-items:flex-start}.account-success>svg{margin-top:3px}.account-dialog{padding:22px!important}.account-dialog .account-field small{font-size:11px}.account-dialog-actions .btn{min-height:42px}.account-form-footer .text-button{min-height:35px}.account-admin-main>.error-banner{flex-wrap:wrap}.account-admin-main>.error-banner .text-button{min-height:30px}}
@media(max-width:380px){.account-card{padding:24px 20px}.account-page{padding:25px 14px}.account-admin-brand{gap:6px}.account-admin-main .page-heading p{max-width:175px}}
@media(prefers-reduced-motion:reduce){.account-spinner{animation:none}.account-dialog{animation:none!important;transition:none!important}}
.feishu-login{margin-top:24px}.feishu-divider{display:flex;align-items:center;gap:12px;color:#64748b;font-size:12px;margin-bottom:18px}.feishu-divider::before,.feishu-divider::after{content:"";height:1px;background:var(--border);flex:1}.feishu-login-button{width:100%;min-height:44px}.feishu-binding-name{font-size:15px;margin-bottom:10px}.feishu-settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px}.feishu-settings{padding:24px;margin-bottom:20px}.feishu-settings-grid .feishu-settings{margin-bottom:0}.feishu-settings h2{font-size:18px;margin-bottom:16px}.feishu-status{font-size:12px;font-weight:400;color:#526a8c;margin-left:10px}.feishu-settings p,.feishu-settings li,.feishu-settings dl{font-size:14px;color:#526a8c;line-height:1.9}.feishu-settings p{margin-bottom:16px}.feishu-settings dt{margin-top:14px;font-size:12px}.feishu-settings dd{margin:0 0 16px;overflow-wrap:anywhere}.feishu-settings code{font-size:12px}.feishu-settings summary{cursor:pointer;font-weight:550;min-height:28px}.feishu-settings ol{padding-left:22px;margin:16px 0}.feishu-deliveries{width:100%;border-collapse:collapse}.feishu-deliveries th{text-align:left}.feishu-deliveries td{vertical-align:top}.feishu-deliveries small{display:block;font-size:12px;color:#64748b;margin-top:5px;max-width:280px;overflow-wrap:anywhere}.feishu-empty{padding:22px 0}.feishu-admin>.error-banner{margin-bottom:20px}@media(max-width:720px){.feishu-settings-grid{grid-template-columns:1fr;gap:16px}.feishu-settings{padding:20px}.feishu-settings p,.feishu-settings li{font-size:13px}}
.feishu-delivery-tools{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:16px}.feishu-delivery-tools h2{margin:0}.feishu-delivery-tools .account-field{margin:0;min-width:190px;font-size:12px}.feishu-delivery-tools select{font-size:14px}.feishu-pagination{display:flex;justify-content:space-between;align-items:center;gap:16px;border-top:1px solid var(--border);padding-top:18px;margin-top:18px}.feishu-pagination>span{color:#526a8c;font-size:12px}.feishu-pagination>div{display:flex;gap:8px}.feishu-pagination .btn{min-height:40px}@media(max-width:720px){.feishu-delivery-tools{align-items:flex-start;flex-direction:column;gap:12px}.feishu-delivery-tools .account-field{width:100%}.feishu-delivery-tools select{font-size:16px}.feishu-pagination{align-items:flex-start;flex-direction:column}.feishu-pagination>div{width:100%}.feishu-pagination .btn{flex:1}}
+24
View File
@@ -0,0 +1,24 @@
import Link from 'next/link';
import { hasAccountPassword, requireUser } from '@/lib/server/auth';
import { getFeishuBinding } from '@/lib/server/feishu-auth';
import { feishuLoginConfigured } from '@/lib/server/feishu-config';
import { FeishuAccount } from '@/components/account/feishu-account';
import { feishuErrorMessage } from '@/lib/feishu';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function FeishuAccountPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const user = await requireUser('/account/feishu');
const params = await searchParams;
const error = feishuErrorMessage(params.feishuError);
return <main className="account-page">
<section className="account-card" aria-labelledby="feishu-title">
<h1 id="feishu-title">飞书绑定</h1>
<p className="account-intro">当前账号:<strong>{user.displayName}({user.username})</strong><br />绑定后可通过飞书登录,继续使用当前账号的需求和权限。</p>
{error && <div className="error-banner" role="alert">{error}</div>}
{params.bound === '1' && <div className="account-success" role="status">飞书账号已绑定,下次可使用飞书登录。</div>}
<FeishuAccount binding={getFeishuBinding(user.userId)} configured={feishuLoginConfigured()} passwordSet={hasAccountPassword(user.userId)} />
<div className="account-form-footer"><Link className="text-button" href="/">返回工作台</Link>{user.role === 'admin' && <Link className="text-button" href="/admin/feishu">飞书集成管理</Link>}</div>
</section>
</main>;
}
+18
View File
@@ -0,0 +1,18 @@
import { PasswordForm } from '@/components/account/password-form';
import { hasAccountPassword, requireUser } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function PasswordPage() {
const user = await requireUser('/account/password');
const passwordSet = hasAccountPassword(user.userId);
return <main className="account-page">
<div className="account-brand brand"><div className="brand-mark" aria-hidden="true"><i /><i /><i /><i /></div><div><strong>需有序</strong><span>需求协作平台</span></div></div>
<section className="account-card account-password-card" aria-labelledby="password-title">
<h1 id="password-title">{!passwordSet ? '设置系统密码' : user.mustChangePassword ? '设置你的密码' : '修改密码'}</h1>
<p className="account-intro">当前账号:<strong>{user.username}</strong></p>
<PasswordForm username={user.username} mustChangePassword={user.mustChangePassword} passwordSet={passwordSet} />
</section>
</main>;
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from 'next/navigation';
import { requireUser } from '@/lib/server/auth';
import { feishuStatus } from '@/lib/server/feishu-notifications';
import { FeishuManagement } from '@/components/account/feishu-management';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function FeishuManagementPage() {
const user = await requireUser('/admin/feishu');
if (user.role !== 'admin') redirect('/');
return <FeishuManagement initial={feishuStatus()} />;
}
+12
View File
@@ -0,0 +1,12 @@
import { redirect } from 'next/navigation';
import { UserManagement } from '@/components/account/user-management';
import { requireUser } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function UsersPage() {
const user = await requireUser('/admin/users');
if (user.role !== 'admin') redirect('/');
return <UserManagement currentUserId={user.userId} />;
}
+14
View File
@@ -0,0 +1,14 @@
import { assertSameOrigin, authFailure, jsonResponse, readJsonObject, requireApiUser, sessionCookie } from '@/lib/server/auth';
import { unbindFeishu } from '@/lib/server/feishu-auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function DELETE(request: Request) {
try {
assertSameOrigin(request);
const user = await requireApiUser();
const body = await readJsonObject(request);
const result = await unbindFeishu(user, body.password, request);
return jsonResponse({ ok: true }, 200, sessionCookie(result.token, request));
} catch (error) { return authFailure(error); }
}
+21
View File
@@ -0,0 +1,21 @@
import { assertSameOrigin, authFailure, AuthError, jsonResponse, readJsonObject, requireApiUser } from '@/lib/server/auth';
import { feishuStatus, parseFeishuDeliveryQuery, retryFeishuNotification, testFeishuBot } from '@/lib/server/feishu-notifications';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(request: Request) {
try { await requireApiUser({ admin: true }); return jsonResponse(feishuStatus(parseFeishuDeliveryQuery(new URL(request.url).searchParams))); }
catch (error) { return authFailure(error); }
}
export async function POST(request: Request) {
try {
assertSameOrigin(request);
await requireApiUser({ admin: true });
const query = parseFeishuDeliveryQuery(new URL(request.url).searchParams);
const body = await readJsonObject(request);
if (body.action === 'test') await testFeishuBot();
else if (body.action === 'retry') retryFeishuNotification(body.id);
else throw new AuthError('不支持的操作。');
return jsonResponse(feishuStatus(query));
} catch (error) { return authFailure(error); }
}
+27
View File
@@ -0,0 +1,27 @@
import { assertSameOrigin, authFailure, createAccount, jsonResponse, listAccounts, readJsonObject, requireApiUser, updateAccount } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const admin = await requireApiUser({ admin: true });
return jsonResponse({ users: listAccounts(admin.userId) });
} catch (error) { return authFailure(error); }
}
export async function POST(request: Request) {
try {
assertSameOrigin(request);
const admin = await requireApiUser({ admin: true });
return jsonResponse({ user: await createAccount(admin.userId, await readJsonObject(request)) }, 201);
} catch (error) { return authFailure(error); }
}
export async function PATCH(request: Request) {
try {
assertSameOrigin(request);
const admin = await requireApiUser({ admin: true });
return jsonResponse({ user: await updateAccount(admin.userId, await readJsonObject(request)) });
} catch (error) { return authFailure(error); }
}
+32
View File
@@ -0,0 +1,32 @@
import { assertSameOrigin, jsonResponse, requireApiUser } from '@/lib/server/auth';
import { deleteStagedAttachment, downloadAttachment, attachmentFailure } from '@/lib/server/attachments';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
type Context = { params: Promise<{ id: string }> };
export async function GET(_request: Request, { params }: Context) {
try {
const user = await requireApiUser();
const { id } = await params;
const { file, bytes } = downloadAttachment(id, user);
const filename = encodeURIComponent(file.name).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
return new Response(new Uint8Array(bytes), { headers: {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="attachment"; filename*=UTF-8''${filename}`,
'Content-Length': String(file.size),
'Cache-Control': 'private, no-store',
'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "sandbox; default-src 'none'",
} });
} catch (error) { return attachmentFailure(error); }
}
export async function DELETE(request: Request, { params }: Context) {
try {
const user = await requireApiUser();
assertSameOrigin(request);
deleteStagedAttachment((await params).id, user.userId);
return jsonResponse({ deleted: true });
} catch (error) { return attachmentFailure(error); }
}
+41
View File
@@ -0,0 +1,41 @@
import { MAX_ATTACHMENT_BYTES } from '@/lib/attachments';
import { AuthError, assertSameOrigin, jsonResponse, requireApiUser } from '@/lib/server/auth';
import { storeUpload, listStagedAttachments, attachmentFailure } from '@/lib/server/attachments';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
const user = await requireApiUser();
assertSameOrigin(request);
const contentType = request.headers.get('content-type') || '';
if (!contentType.toLowerCase().startsWith('multipart/form-data;')) throw new AuthError('请选择文件后上传。', 415);
const limit = MAX_ATTACHMENT_BYTES + 65536;
if (Number(request.headers.get('content-length')) > limit) throw new AuthError('单个文件不能超过 20 MB。', 413);
const reader = request.body?.getReader();
if (!reader) throw new AuthError('没有收到文件,请重新选择。');
const chunks: Uint8Array[] = [];
let size = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > limit) { await reader.cancel(); throw new AuthError('单个文件不能超过 20 MB。', 413); }
chunks.push(value);
}
let form: FormData;
try { form = await new Response(new Uint8Array(Buffer.concat(chunks)), { headers: { 'Content-Type': contentType } }).formData(); }
catch { throw new AuthError('上传内容不完整,请重新选择文件上传。'); }
const files = form.getAll('file');
if (files.length !== 1 || !(files[0] instanceof File)) throw new AuthError('每次上传一个文件。');
const file = files[0];
if (file.size > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413);
return jsonResponse({ attachment: storeUpload(user.userId, file.name, new Uint8Array(await file.arrayBuffer())) }, 201);
} catch (error) { return attachmentFailure(error); }
}
export async function GET() {
try { return jsonResponse({ attachments: listStagedAttachments((await requireApiUser()).userId) }); }
catch (error) { return attachmentFailure(error); }
}
+23
View File
@@ -0,0 +1,23 @@
import { appPath } from '@/lib/base-path';
import { sessionCookie } from '@/lib/server/auth';
import { applicationOrigin } from '@/lib/server/database';
import { completeFeishuAuth, consumeFeishuState, FeishuAuthError, feishuStateCookie } from '@/lib/server/feishu-auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(request: Request) {
const headers = new Headers({ 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
let binding = false;
try {
const state = consumeFeishuState(request);
binding = Boolean(state.account_id);
headers.append('Set-Cookie', feishuStateCookie(''));
const result = await completeFeishuAuth(request, state);
if (result.token) headers.append('Set-Cookie', sessionCookie(result.token, request));
headers.set('Location', applicationOrigin() + appPath(result.returnTo + (result.bound ? '?bound=1' : '')));
} catch (error) {
const code = error instanceof FeishuAuthError ? error.code : 'failed';
headers.set('Location', applicationOrigin() + appPath(`${binding ? '/account/feishu' : '/login'}?feishuError=${code}`));
}
return new Response(null, { status: 303, headers });
}
+22
View File
@@ -0,0 +1,22 @@
import { appPath } from '@/lib/base-path';
import { assertSameOrigin, AuthError } from '@/lib/server/auth';
import { applicationOrigin } from '@/lib/server/database';
import { beginFeishuAuth, FeishuAuthError } from '@/lib/server/feishu-auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
let intent = 'login';
try {
assertSameOrigin(request);
const raw = await request.text();
if (raw.length > 8192) throw new FeishuAuthError('failed');
const form = new URLSearchParams(raw);
intent = form.get('intent') || 'login';
const result = beginFeishuAuth(request, intent, form.get('next'));
return new Response(null, { status: 303, headers: { Location: result.url, 'Set-Cookie': result.cookie, 'Cache-Control': 'no-store' } });
} catch (error) {
const code = error instanceof FeishuAuthError ? error.code : error instanceof AuthError && error.status === 429 ? 'rate_limited' : error instanceof AuthError && error.status === 403 ? 'source' : 'failed';
return new Response(null, { status: 303, headers: { Location: applicationOrigin() + appPath(`${intent === 'bind' ? '/account/feishu' : '/login'}?feishuError=${code}`), 'Cache-Control': 'no-store' } });
}
}
+13
View File
@@ -0,0 +1,13 @@
import { assertSameOrigin, authFailure, jsonResponse, loginWithPassword, readJsonObject, sessionCookie } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
assertSameOrigin(request);
const body = await readJsonObject(request);
const { user, token } = await loginWithPassword(body.username, body.password, request);
return jsonResponse({ user }, 200, sessionCookie(token, request));
} catch (error) { return authFailure(error); }
}
+12
View File
@@ -0,0 +1,12 @@
import { assertSameOrigin, authFailure, jsonResponse, logoutCurrentSession, sessionCookie } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
assertSameOrigin(request);
await logoutCurrentSession();
return jsonResponse({ ok: true }, 200, sessionCookie('', request));
} catch (error) { return authFailure(error); }
}
+9
View File
@@ -0,0 +1,9 @@
import { authFailure, jsonResponse, requireApiUser } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET() {
try { return jsonResponse({ user: await requireApiUser({ allowPasswordChange: true }) }); }
catch (error) { return authFailure(error); }
}
+14
View File
@@ -0,0 +1,14 @@
import { assertSameOrigin, authFailure, changeAccountPassword, jsonResponse, readJsonObject, requireApiUser, sessionCookie } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
try {
assertSameOrigin(request);
const current = await requireApiUser({ allowPasswordChange: true });
const body = await readJsonObject(request);
const { user, token } = await changeAccountPassword(current.userId, body.currentPassword, body.newPassword);
return jsonResponse({ user }, 200, sessionCookie(token, request));
} catch (error) { return authFailure(error); }
}
+53 -25
View File
@@ -1,50 +1,78 @@
import { env } from 'cloudflare:workers';
import { getChatGPTUser } from '../../chatgpt-auth';
import { getDatabase } from '@/lib/server/database';
import { AuthError, getCurrentUser, isSameOrigin, type AuthUser } from '@/lib/server/auth';
import { fieldSchema, missingFields, type Demand } from '@/lib/demand';
import { invalidateProposal } from '@/lib/demand-review';
import { applyReviewAction } from '@/lib/server/demand-review';
import { withDefaultDeveloper, canTakeOverDevelopment } from '@/lib/server/default-developer';
import { attachmentIds, syncDemandAttachments, commitDemandAttachments } from '@/lib/server/attachments';
import { readableDemandWhere, readableDemandBindings } from '@/lib/server/demand-access';
import { workflowActions, applyWorkflowAction } from '@/lib/server/workflow';
import { queueDemandNotification } from '@/lib/server/feishu-notifications';
export const dynamic='force-dynamic';
export const runtime='nodejs';
const fail=(error:string,status=400)=>Response.json({error},{status,headers:{'Cache-Control':'no-store'}});
function db(){if(!env.DB)throw new Error('Database unavailable');return env.DB;}
const db=getDatabase;
const reviewActions=new Set(['assign-developer','take-over-development','propose-solution','confirm-solution','return-solution']);
const visibleDemand=(record:Demand,ownerId:string,user:AuthUser):Demand=>{const demand=withDefaultDeveloper(record);return {...demand,access:{business:ownerId===user.userId,developer:demand.status!=='草稿'&&demand.review?.developer.userId===user.userId,canTakeOverDevelopment:canTakeOverDevelopment(demand,user)}};};
export async function GET(){
const user=await getChatGPTUser();if(!user)return fail('请先登录后查看你的需求。',401);
try{const result=await db().prepare('SELECT payload, revision FROM demands WHERE owner_id = ? ORDER BY updated_at DESC').bind(user.userId).all<{payload:string;revision:number}>();return Response.json({demands:result.results.map(r=>({...JSON.parse(r.payload),revision:r.revision}))},{headers:{'Cache-Control':'no-store'}});}
const user=await getCurrentUser();if(!user)return fail('登录已失效,请重新登录。',401);if(user.mustChangePassword)return fail('请先修改初始密码。',403);
try{const result=await db().prepare(`SELECT payload, revision, owner_id FROM demands WHERE ${readableDemandWhere} ORDER BY updated_at DESC`).bind(...readableDemandBindings(user)).all<{payload:string;revision:number;owner_id:string}>();return Response.json({demands:result.results.map(r=>visibleDemand({...JSON.parse(r.payload),revision:r.revision},r.owner_id,user))},{headers:{'Cache-Control':'no-store'}});}
catch(e){console.error('Demand load failed',e);return fail('需求暂时无法加载,请稍后重试。',503);}
}
export async function POST(request:Request){
const user=await getChatGPTUser();if(!user)return fail('请先登录后保存需求。',401);
if(request.headers.get('origin')&&request.headers.get('origin')!==new URL(request.url).origin)return fail('请求来源无效。',403);
const user=await getCurrentUser();if(!user)return fail('登录已失效,请重新登录。',401);if(user.mustChangePassword)return fail('请先修改初始密码。',403);
if(!isSameOrigin(request))return fail('请求来源无效。',403);
try{
const raw=await request.text();if(raw.length>80000)return fail('内容过长,请通过参考链接提供较大材料。',413);
const raw=await request.text();if(raw.length>600000)return fail('内容过长,请通过参考链接提供较大材料。',413);
let body;try{body=JSON.parse(raw);}catch{return fail('提交内容格式无效。');}
if(!body||typeof body!=='object')return fail('提交内容格式无效。');
const {action,id,revision}=body;const now=new Date().toISOString();let record:Demand;
const {action,id,revision}=body;const selectedAttachments=['create','update'].includes(action)?attachmentIds(body.attachmentIds):undefined;const now=new Date().toISOString();let record:Demand;let ownerId=user.userId;
if(action==='create'){
const parsed=fieldSchema.safeParse(body.fields);if(!parsed.success)return fail('请检查字段格式及内容长度。');
const fields=parsed.data;const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('登记方式无效。');
const fields=parsed.data;if(fields.scope||fields.outOfScope)return fail('实施方案请由指定的开发责任人在需求评审中填写。',403);const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('登记方式无效。');
if(!fields.title)return fail('请先填写需求标题。');const missing=mode==='draft'?[]:missingFields(fields,mode==='review');if(missing.length)return fail('请补充:'+missing.join('、'));
if(mode!=='draft'){const all=await db().prepare('SELECT payload FROM demands WHERE owner_id = ?').bind(user.userId).all<{payload:string}>();if(all.results.some(r=>{const d=JSON.parse(r.payload);return !['草稿','已取消','已完成'].includes(d.status)&&d.fields.title===fields.title;}))return fail('已存在同名需求,请先检查现有记录,避免重复登记。',409);}
record={id:'REQ-'+now.slice(0,10).replaceAll('-','')+'-'+crypto.randomUUID().slice(0,8).toUpperCase(),revision:1,fields,status:mode==='draft'?'草稿':'待评审',reviewReady:mode==='review',createdAt:now,updatedAt:now,history:[{time:now,actor:user.displayName,action:mode==='draft'?'保存草稿':mode==='review'?'提交评审':'登记需求',detail:mode==='review'?'业务材料已齐备,等待负责人评审。':'已保存业务需求信息。'}],changes:[]};
await db().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)').bind(record.id,user.userId,JSON.stringify(record),now).run();
record={id:'REQ-'+now.slice(0,10).replaceAll('-','')+'-'+crypto.randomUUID().slice(0,8).toUpperCase(),revision:1,fields,status:mode==='draft'?'草稿':'待评审',reviewReady:mode==='review',createdAt:now,updatedAt:now,history:[{time:now,actor:user.displayName,action:mode==='draft'?'保存草稿':mode==='review'?'提交评审':'登记需求',detail:mode==='review'?'业务材料已齐备,实施范围与功能说明、范围外事项待开发责任人在需求评审时提出方案,并与业务方确认。':'已保存业务需求信息。'}],changes:[]};
record=withDefaultDeveloper(record);
db().transaction(()=>{
syncDemandAttachments(record,ownerId,selectedAttachments??[],now);
db().prepare('INSERT INTO demands (id, owner_id, payload, revision, updated_at) VALUES (?, ?, ?, 1, ?)').bind(record.id,user.userId,JSON.stringify(record),now).run();
commitDemandAttachments(record,ownerId);
queueDemandNotification(record);
});
}else{
if(typeof id!=='string'||!Number.isInteger(revision))return fail('需求编号或版本无效。');
const row=await db().prepare('SELECT payload, revision FROM demands WHERE id = ? AND owner_id = ?').bind(id,user.userId).first<{payload:string;revision:number}>();if(!row)return fail('找不到该需求或你没有访问权限。',404);if(row.revision!==revision)return fail('需求已更新,请刷新后再操作;本次输入尚未保存。',409);
record=JSON.parse(row.payload);let label='',detail='';
if(action==='update'){
const row=await db().prepare(`SELECT payload, revision, owner_id FROM demands WHERE id = ? AND ${readableDemandWhere}`).bind(id,...readableDemandBindings(user)).first<{payload:string;revision:number;owner_id:string}>();if(!row)return fail('找不到该需求或你没有访问权限。',404);
record=withDefaultDeveloper(JSON.parse(row.payload));ownerId=row.owner_id;
if(ownerId!==user.userId&&record.review?.developer.userId!==user.userId&&!(action==='take-over-development'&&canTakeOverDevelopment(record,user)))return fail('找不到该需求或你没有访问权限。',404);
if(row.revision!==revision)return fail('需求已更新,请刷新后再操作;本次输入尚未保存。',409);
let label='',detail='';
if(ownerId!==user.userId&&!reviewActions.has(action)&&!workflowActions.has(action))return fail('开发责任人只能提交评审方案,业务操作由需求登记账号执行。',403);
if(workflowActions.has(action)){
({label,detail}=applyWorkflowAction(record,ownerId,user,body,now));
}else if(reviewActions.has(action)){
({label,detail}=applyReviewAction(record,ownerId,user,body,now));
}else if(action==='update'){
if(!['草稿','待评审'].includes(record.status))return fail('已确认的需求请通过「提出变更」进行调整。',409);
const parsed=fieldSchema.safeParse(body.fields);if(!parsed.success)return fail('请检查字段格式及内容长度。');const mode=body.mode;if(!['draft','register','review'].includes(mode))return fail('保存方式无效。');if(record.status!=='草稿'&&mode==='draft')return fail('正式需求不能退回草稿。');if(!parsed.data.title)return fail('请填写需求标题。');const missing=mode==='draft'?[]:missingFields(parsed.data,mode==='review');if(missing.length)return fail('请补充:'+missing.join('、'));
if(mode!=='draft'){const peers=await db().prepare('SELECT id, payload FROM demands WHERE owner_id = ? AND id != ?').bind(user.userId,id).all<{id:string;payload:string}>();if(peers.results.some(r=>{const p=JSON.parse(r.payload);return !['草稿','已取消','已完成'].includes(p.status)&&p.fields.title===parsed.data.title;}))return fail('已存在同名需求,请核对后合并到原记录。',409);}
if(parsed.data.scope!==record.fields.scope||parsed.data.outOfScope!==record.fields.outOfScope)return fail('业务信息编辑不能修改评审方案,请由开发责任人提交。',403);
const businessChanged=Object.entries(parsed.data).some(([key,value])=>value!==record.fields[key as keyof typeof record.fields]);
if(businessChanged)invalidateProposal(record,now,'业务需求已修改,需开发责任人重新提交方案并由业务方确认。');
record.fields=parsed.data;record.status=mode==='draft'?'草稿':'待评审';record.reviewReady=mode==='review';label=mode==='review'?'补充材料并提交评审':'更新需求';detail='业务内容已更新,文档版本 '+record.fields.version+'。';
}else if(action==='cancel'){
if(['已上线','已完成','已取消'].includes(record.status))return fail('当前状态不能取消。',409);if(typeof body.reason!=='string'||!body.reason.trim()||body.reason.length>3000)return fail('请填写终止原因(3000 字以内)。');record.status='已取消';label='确认取消需求';detail=body.reason.trim();
}else if(action==='change'){
if(!['已排期','开发中','待验收','待发布','已上线'].includes(record.status))return fail('当前状态不能提出变更;待评审需求请直接补充信息。',409);if(typeof body.content!=='string'||typeof body.reason!=='string'||!body.content.trim()||!body.reason.trim()||body.content.length>5000||body.reason.length>3000)return fail('请填写变更内容(5000 字以内)和原因(3000 字以内)。');record.changes.push({time:now,content:body.content.trim(),reason:body.reason.trim(),actor:user.displayName,status:'待开发评估与双方确认',originalVersion:record.fields.version,originalFields:structuredClone(record.fields)});label='提出需求变更';detail=body.content.trim()+';原因:'+body.reason.trim()+'。原范围与版本保留,待评估确认后实施。';
}else if(action==='accept'){
if(record.status!=='待验收'||!record.acceptance)return fail('该需求尚未进入可验收阶段。',409);
const results=body.results;if(!Array.isArray(results)||results.length!==record.acceptance.items.length||!results.length||results.some(r=>!['通过','不通过'].includes(r)))return fail('请逐项填写验收结果。');if(typeof body.notes!=='string'||!body.notes.trim()||body.notes.length>5000)return fail('请填写遗留问题及处理计划,无则填“无”。');if(body.confirm!==true)return fail('请明确确认本次验收结论。');if(body.testVersion!==record.acceptance.testVersion||body.version!==record.fields.version)return fail('验收版本已变化,请重新核对。',409);
const passed=results.every(r=>r==='通过');record.status=passed?'待发布':'开发中';record.acceptanceRecords??=[];record.acceptanceRecords.push({time:now,actor:user.displayName,version:record.fields.version,testVersion:record.acceptance.testVersion,results,notes:body.notes.trim(),passed,items:record.acceptance.items.map((item,i)=>({...item,result:results[i]})),environment:record.acceptance.environment});label=passed?'业务验收通过':'业务验收未通过';detail=`需求文档 ${record.fields.version};测试版本 ${record.acceptance.testVersion};${passed?'全部验收项通过,同意按约定计划上线。':'退回开发中修复,需重新提测。'}遗留问题及计划:${body.notes.trim()}`;
if(['已上线','已完成','已取消'].includes(record.status))return fail('当前状态不能取消。',409);if(typeof body.reason!=='string'||!body.reason.trim()||body.reason.length>3000)return fail('请填写终止原因(3000 字以内)。');record.status='已取消';for(const change of record.changes){if(['待开发评估与双方确认','待开发评估','待业务确认'].includes(change.status))change.status='随需求取消';}delete record.blocked;if(record.delivery)delete record.delivery.blocker;label='确认取消需求';detail=body.reason.trim();
}else return fail('不支持的操作。');
record=withDefaultDeveloper(record);
db().transaction(()=>{
if(action==='update'&&syncDemandAttachments(record,ownerId,selectedAttachments,now))detail+='参考附件已更新;已有评审方案需重新提交确认。';
record.revision=row.revision+1;record.updatedAt=now;record.history.push({time:now,actor:user.displayName,action:label,detail});
const updated=await db().prepare('UPDATE demands SET payload = ?, revision = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND revision = ?').bind(JSON.stringify(record),record.revision,now,id,user.userId,row.revision).run();if(updated.meta.changes!==1)return fail('需求已被更新,请刷新后重试。',409);
const updated=db().prepare('UPDATE demands SET payload = ?, revision = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND revision = ?').bind(JSON.stringify(record),record.revision,now,id,ownerId,row.revision).run();
if(updated.meta.changes!==1)throw new AuthError('需求已被更新,请刷新后重试。',409);
commitDemandAttachments(record,ownerId);
queueDemandNotification(record);
});
}
return Response.json({demand:record},{headers:{'Cache-Control':'no-store'}});
}catch(e){console.error('Demand save failed',e);return fail('保存失败,你的输入仍保留在页面中,请稍后重试。',503);}
return Response.json({demand:visibleDemand(record,ownerId,user)},{headers:{'Cache-Control':'no-store'}});
}catch(e){if(e instanceof AuthError)return fail(e.message,e.status);console.error('Demand save failed',e);return fail('保存失败,你的输入仍保留在页面中,请稍后重试。',503);}
}
+25
View File
@@ -0,0 +1,25 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { getCurrentUser } from '@/lib/server/auth';
import { findDocument } from '@/lib/documents';
export const runtime='nodejs';
export const dynamic='force-dynamic';
export async function GET(request:Request,{params}:{params:Promise<{name:string}>}) {
const user=await getCurrentUser();
if(!user)return Response.json({error:'请先登录。'},{status:401,headers:{'Cache-Control':'no-store'}});
if(user.mustChangePassword)return Response.json({error:'请先修改初始密码。'},{status:403,headers:{'Cache-Control':'no-store'}});
const {name}=await params;const document=findDocument(name);
if(!document)return Response.json({error:'找不到该文档。'},{status:404});
const format=new URL(request.url).searchParams.get('format')||'markdown';
if(!['json','markdown','docx'].includes(format))return Response.json({error:'不支持的文档格式。'},{status:400});
try{
if(format==='docx'){
const filename=document.filename.replace(/\.md$/,'.docx');
const data=await readFile(join(process.cwd(),'content','word',filename));
return new Response(new Uint8Array(data),{headers:{'Content-Type':'application/vnd.openxmlformats-officedocument.wordprocessingml.document','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
}
const content=await readFile(join(process.cwd(),'content','docs',document.filename),'utf8');
if(format==='json')return Response.json({id:document.id,title:document.title,content},{headers:{'Cache-Control':'private, no-store'}});
return new Response(content,{headers:{'Content-Type':'text/markdown; charset=utf-8','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(document.filename)}`,'Cache-Control':'private, no-store'}});
}catch(error){console.error('Document read failed',error);return Response.json({error:'文档暂时无法打开或下载,请稍后重试。'},{status:503,headers:{'Cache-Control':'no-store'}});}
}
+7
View File
@@ -0,0 +1,7 @@
import { getDatabase } from '@/lib/server/database';
export const runtime='nodejs';
export const dynamic='force-dynamic';
export async function GET(){
try{getDatabase().prepare('SELECT 1').first();return Response.json({status:'ok'},{headers:{'Cache-Control':'no-store'}});}
catch{ return Response.json({status:'unavailable'},{status:503,headers:{'Cache-Control':'no-store'}});}
}
-90
View File
@@ -1,90 +0,0 @@
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export type ChatGPTUser = {
userId: string;
displayName: string;
email: string;
fullName: string | null;
};
const USER_ID_HEADER = "oai-authenticated-user-id";
const USER_EMAIL_HEADER = "oai-authenticated-user-email";
const USER_FULL_NAME_HEADER = "oai-authenticated-user-full-name";
const USER_FULL_NAME_ENCODING_HEADER =
"oai-authenticated-user-full-name-encoding";
const PERCENT_ENCODED_UTF8 = "percent-encoded-utf-8";
const SIGN_IN_PATH = "/signin-with-chatgpt";
const SIGN_OUT_PATH = "/signout-with-chatgpt";
const CALLBACK_PATH = "/callback";
export async function getChatGPTUser(): Promise<ChatGPTUser | null> {
const requestHeaders = await headers();
const userId = requestHeaders.get(USER_ID_HEADER);
const email = requestHeaders.get(USER_EMAIL_HEADER);
if (!userId || !email) return null;
const encodedFullName = requestHeaders.get(USER_FULL_NAME_HEADER);
const fullName =
encodedFullName &&
requestHeaders.get(USER_FULL_NAME_ENCODING_HEADER) === PERCENT_ENCODED_UTF8
? safeDecodeURIComponent(encodedFullName)
: null;
return {
userId,
displayName: fullName ?? email,
email,
fullName,
};
}
export async function requireChatGPTUser(
returnTo: string,
): Promise<ChatGPTUser> {
const user = await getChatGPTUser();
if (user) return user;
redirect(chatGPTSignInPath(returnTo));
}
export function chatGPTSignInPath(returnTo: string): string {
const safeReturnTo = safeRelativeReturnPath(returnTo);
return `${SIGN_IN_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`;
}
export function chatGPTSignOutPath(returnTo = "/"): string {
const safeReturnTo = safeRelativeReturnPath(returnTo);
return `${SIGN_OUT_PATH}?return_to=${encodeURIComponent(safeReturnTo)}`;
}
function safeRelativeReturnPath(value: string): string {
if (!value.startsWith("/") || value.startsWith("//")) return "/";
let url: URL;
try {
url = new URL(value, "https://app.local");
} catch {
return "/";
}
if (url.origin !== "https://app.local") return "/";
if (isReservedAuthPath(url.pathname)) return "/";
return `${url.pathname}${url.search}${url.hash}`;
}
function isReservedAuthPath(pathname: string): boolean {
return (
pathname === SIGN_IN_PATH ||
pathname === SIGN_OUT_PATH ||
pathname === CALLBACK_PATH
);
}
function safeDecodeURIComponent(value: string): string | null {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
+30 -1
View File
@@ -11,9 +11,38 @@
@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}
.icon-button{border:0;background:none;border-radius:6px;display:grid;place-items:center;padding:7px;color:#778aa6}.icon-button:hover{background:#eff4fb;color:var(--ink)}.demand-modal{display:flex!important;flex-direction:column;gap:0!important;padding:0!important;width:min(960px,calc(100vw - 48px))!important;max-width:960px!important;max-height:calc(100dvh - 64px)!important;border-radius:12px!important;overflow:hidden;background:white!important;box-shadow:0 22px 80px #17346230!important;color:var(--ink)}.modal-heading{padding:23px 27px;display:flex;gap:13px;align-items:center;border-bottom:1px solid var(--border);flex-shrink:0}.modal-icon{height:43px;width:43px;border-radius:9px;background:#edf4ff;color:var(--blue);display:grid;place-items:center}.modal-heading .icon-button{margin-left:auto;align-self:flex-start}.modal-title{font-size:21px!important;line-height:1.4;font-weight:650}.modal-subtitle{color:var(--muted)!important;font-size:13px;margin-top:3px}.form-steps{display:flex;justify-content:space-between;border-bottom:1px solid var(--border);padding:20px 30px;gap:15px;flex-shrink:0;background:#fbfcff}.form-steps button{display:flex;align-items:center;gap:9px;border:0;background:none;color:#8290a7;font-size:13px}.form-steps b{font-weight:500}.form-steps span{width:24px;height:24px;display:grid;place-items:center;border:1px solid #dce3ee;border-radius:50%;font-size:12px;background:white}.form-steps .current{color:var(--blue)}.form-steps .current span{background:var(--blue);color:white;border-color:var(--blue)}.form-steps .done{color:#4777c5}.form-steps .done span{color:var(--blue);border-color:#c6d9fa;background:#eef4ff}.modal-scroll{overflow-y:auto;min-height:0;overscroll-behavior:contain}.form-content{padding:26px 32px 30px}.form-section-heading{margin-bottom:24px}.form-section-heading h2{font-size:19px}.form-section-heading p{color:var(--muted);font-size:13px;margin-top:5px}.form-grid{display:grid;grid-template-columns:1fr 1fr;column-gap:22px;row-gap:20px}.form-field{display:flex;flex-direction:column;gap:7px;min-width:0;font-size:14px}.form-field>span{font-weight:550}.form-field em{font-style:normal;color:#e06d70;padding-left:5px}.form-field input,.form-field textarea,.form-field select{width:100%;border:1px solid #d9e2f0;border-radius:6px;padding:10px 12px;background:white;min-height:42px;font-size:14px;color:var(--ink);resize:vertical}.form-field input::placeholder,.form-field textarea::placeholder{color:#9aa6b9}.form-field small{color:#8794a8;font-size:12px;line-height:1.6}.span-two{grid-column:span 2}.check-field{display:flex;gap:9px;align-items:center;font-size:14px;color:#4e6080}.check-field input{accent-color:var(--blue);width:16px;height:16px;flex-shrink:0}.info-banner{display:flex;gap:9px;align-items:flex-start;border-radius:6px;background:#f0f6ff;color:#5173a3;padding:12px 14px;font-size:13px;line-height:1.6}.info-banner svg{margin-top:2px}.form-content>.info-banner{margin-bottom:20px}.error-banner{display:flex;align-items:flex-start;gap:9px;background:#fff0f0;color:#ba404b;padding:12px 14px;border:1px solid #f5cecf;border-radius:6px;margin-bottom:20px;font-size:13px}.error-banner svg{margin-top:2px}.modal-footer{border-top:1px solid var(--border);padding:17px 27px;display:flex;align-items:center;justify-content:space-between;gap:18px;flex-shrink:0;background:#fff}.footer-left,.footer-right{display:flex;gap:15px;align-items:center}.exit-banner{display:flex;gap:14px;align-items:center;padding:16px;border:1px solid #f1dcae;background:#fff9ed;border-radius:7px;margin-bottom:20px;font-size:13px}.exit-banner strong{font-size:14px}.exit-banner p{font-size:12px;color:#9d8254;margin-top:3px}.exit-banner>div{margin-right:auto}.danger-text{color:#bd4b57!important}.toast{position:fixed;z-index:100;bottom:30px;left:calc(50% + 100px);transform:translateX(-50%);background:#17315b;color:white;display:flex;gap:9px;align-items:center;border-radius:8px;padding:13px 22px;box-shadow:0 6px 28px #13234d20;font-size:14px;max-width:calc(100vw - 36px)}.page-error{margin-bottom:18px}.page-error button{margin-left:auto;color:inherit;text-decoration:underline}.loading-bar{height:3px;background:linear-gradient(90deg,#1762f5,#95baff);position:fixed;top:0;left:0;right:0;z-index:110;animation:loading 1.2s infinite alternate}@keyframes loading{from{opacity:.25}to{opacity:1}}
@media(max-width:720px){.demand-modal{width:calc(100vw - 20px)!important;max-height:calc(100dvh - 24px)!important}.modal-heading{padding:18px;gap:9px}.modal-title{font-size:19px!important}.modal-subtitle{font-size:11px}.modal-icon{display:none}.form-steps{padding:16px 18px;gap:5px}.form-steps button{flex-direction:column;gap:5px;font-size:10px}.form-steps b{max-width:80px}.form-content{padding:20px 18px}.form-grid{grid-template-columns:1fr;gap:18px}.span-two{grid-column:span 1}.form-field{font-size:13px}.form-field input,.form-field select,.form-field textarea{font-size:16px}.modal-footer{padding:13px;gap:10px;align-items:center;flex-wrap:wrap}.modal-footer .btn{font-size:12px;padding:8px 10px;min-height:37px}.footer-left,.footer-right{gap:10px}.back-button{font-size:12px}.footer-right{margin-left:auto}.exit-banner{flex-wrap:wrap}.exit-banner>div{width:100%}.toast{left:50%;font-size:13px;bottom:20px}.form-section-heading h2{font-size:18px}.form-section-heading p{font-size:12px}}
.detail-heading{padding:20px 28px 22px;flex-shrink:0}.detail-eyeline{display:flex;align-items:center;gap:12px;margin-bottom:11px;font-size:12px;color:var(--muted)}.detail-eyeline>.icon-button{margin-left:auto}.detail-title{font-size:23px!important;font-weight:650;line-height:1.5}.detail-description{color:var(--muted);font-size:13px;margin-top:7px}.detail-description>span{padding:0 7px;color:#b0bdcf}.demo-tag{color:#8e9bb0;border:1px solid var(--border);border-radius:4px;padding:1px 7px;font-size:11px}.detail-progress{display:flex;justify-content:space-between;gap:8px;padding:19px 29px;background:#f8faff;border-top:1px solid var(--border);border-bottom:1px solid var(--border);flex-shrink:0}.detail-progress>div{display:flex;align-items:center;gap:7px;font-size:12px;position:relative;color:#8d9bb0}.detail-progress span{height:20px;width:20px;display:grid;place-items:center;border:1px solid #d9e2ef;border-radius:50%;font-size:10px}.detail-progress b{font-weight:400;white-space:nowrap}.detail-progress .done{color:#4e7bc5}.detail-progress .current{color:var(--blue);font-weight:600}.detail-progress .current span{background:var(--blue);border-color:var(--blue);color:white}.detail-progress .done span{border:0}.detail-tabs{padding-left:28px;gap:30px;flex-shrink:0}.detail-tabs small{padding-left:6px}.detail-content{padding:25px 29px 32px}.detail-info{margin-bottom:20px}.detail-overview{display:grid;grid-template-columns:repeat(4,1fr);gap:15px;padding:0 0 22px;border-bottom:1px solid var(--border)}.detail-field>span{font-size:12px;color:#8896ab}.detail-field p{font-size:14px;line-height:1.9;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:5px}.detail-section{padding:25px 0;border-bottom:1px solid var(--border)}.detail-section:last-child{border:0;padding-bottom:0}.detail-section h2{font-size:17px;margin-bottom:19px}.detail-section .detail-field{margin-bottom:18px}.detail-section .detail-field:last-child{margin:0}.plan-strip{background:#f3f7ff;padding:17px 20px;border-radius:7px;margin-top:24px}.plan-strip>h3{font-size:14px;display:flex;align-items:center;gap:8px;color:#446aa3;margin-bottom:12px}.plan-strip>div{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.plan-strip .detail-field p{font-size:13px}.timeline{padding:4px 0 4px 17px}.timeline article{position:relative;padding:0 0 30px 24px;border-left:1px solid #dfe8f6}.timeline article:last-child{border-color:transparent;padding-bottom:5px}.timeline-dot{width:9px;height:9px;position:absolute;left:-5px;top:7px;border:2px solid #fff;background:#90ade0;border-radius:50%;box-shadow:0 0 0 2px #e5edf9}.timeline article:first-child .timeline-dot{background:var(--blue)}.timeline-meta{display:flex;justify-content:space-between;gap:15px}.timeline-meta h3{font-size:14px}.timeline-meta time{font-size:12px;color:#8f9cb0}.timeline article p{font-size:14px;margin:8px 0;color:#536783;white-space:pre-wrap}.timeline article>span{font-size:12px;color:#8d9bb0}.action-form>h2{font-size:20px}.action-form>p{color:var(--muted);font-size:14px;margin:8px 0 25px}.action-form .form-field{margin-top:20px}.danger-button{background:#be4754;color:white;border-color:#be4754}.danger-button:hover{background:#a43844;color:white}.change-record{border:1px solid var(--border);border-radius:7px;padding:20px;margin-bottom:15px}.change-record>div:first-child{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.change-record .detail-field{margin-bottom:15px}.acceptance-intro h2{font-size:19px}.acceptance-intro>p{font-size:13px;color:var(--muted);margin:7px 0 18px}.acceptance-intro>p span{padding:0 8px}.acceptance-intro .detail-field{margin-top:12px}.deadline{color:#a67a28;font-size:12px;display:flex;align-items:center;gap:8px;padding:12px 0 20px}.acceptance-item{border:1px solid var(--border);border-radius:7px;padding:18px;margin-bottom:13px}.acceptance-item-top{display:flex;align-items:center;gap:12px;margin-bottom:15px}.acceptance-item-top>span{color:var(--blue);font-size:12px}.acceptance-item-top strong{font-size:14px;font-weight:550}.acceptance-item-top select{margin-left:auto;padding:5px 11px;border:1px solid var(--border);border-radius:5px;background:#fff;font-size:13px}.acceptance-item p{display:flex;gap:15px;font-size:14px;margin-top:6px;color:#475c7c}.acceptance-item p>span{font-size:12px;white-space:nowrap;color:#8a98ab;min-width:58px}.acceptance-confirm{margin-top:24px}.acceptance-confirm .check-field{margin:20px 0;font-size:13px;align-items:flex-start}.acceptance-confirm .check-field input{margin-top:4px}.acceptance-record{border-left:3px solid #7fa2d6;padding:16px 20px;margin-top:25px;background:#f7faff;font-size:13px}.acceptance-record h3{font-size:15px;margin-bottom:7px}.acceptance-record p{color:#637896;margin-top:5px}.acceptance-record>span{color:#8c9bb0;font-size:12px;display:block;margin-top:10px}.guide-grid{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:24px}.guide-main{padding:27px}.guide-main>h2{font-size:20px;margin-bottom:15px}.guiLine truncated
.detail-heading{padding:20px 28px 22px;flex-shrink:0}.detail-eyeline{display:flex;align-items:center;gap:12px;margin-bottom:11px;font-size:12px;color:var(--muted)}.detail-eyeline>.icon-button{margin-left:auto}.detail-title{font-size:23px!important;font-weight:650;line-height:1.5}.detail-description{color:var(--muted);font-size:13px;margin-top:7px}.detail-description>span{padding:0 7px;color:#b0bdcf}.detail-progress{display:flex;justify-content:space-between;gap:8px;padding:19px 29px;background:#f8faff;border-top:1px solid var(--border);border-bottom:1px solid var(--border);flex-shrink:0}.detail-progress>div{display:flex;align-items:center;gap:7px;font-size:12px;position:relative;color:#8d9bb0}.detail-progress span{height:20px;width:20px;display:grid;place-items:center;border:1px solid #d9e2ef;border-radius:50%;font-size:10px}.detail-progress b{font-weight:400;white-space:nowrap}.detail-progress .done{color:#4e7bc5}.detail-progress .current{color:var(--blue);font-weight:600}.detail-progress .current span{background:var(--blue);border-color:var(--blue);color:white}.detail-progress .done span{border:0}.detail-tabs{padding-left:28px;gap:30px;flex-shrink:0}.detail-tabs small{padding-left:6px}.detail-content{padding:25px 29px 32px}.detail-overview{display:grid;grid-template-columns:repeat(4,1fr);gap:15px;padding:0 0 22px;border-bottom:1px solid var(--border)}.detail-field>span{font-size:12px;color:#8896ab}.detail-field p{font-size:14px;line-height:1.9;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:5px}.detail-section{padding:25px 0;border-bottom:1px solid var(--border)}.detail-section:last-child{border:0;padding-bottom:0}.detail-section h2{font-size:17px;margin-bottom:19px}.detail-section .detail-field{margin-bottom:18px}.detail-section .detail-field:last-child{margin:0}.plan-strip{background:#f3f7ff;padding:17px 20px;border-radius:7px;margin-top:24px}.plan-strip>h3{font-size:14px;display:flex;align-items:center;gap:8px;color:#446aa3;margin-bottom:12px}.plan-strip>div{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.plan-strip .detail-field p{font-size:13px}.timeline{padding:4px 0 4px 17px}.timeline article{position:relative;padding:0 0 30px 24px;border-left:1px solid #dfe8f6}.timeline article:last-child{border-color:transparent;padding-bottom:5px}.timeline-dot{width:9px;height:9px;position:absolute;left:-5px;top:7px;border:2px solid #fff;background:#90ade0;border-radius:50%;box-shadow:0 0 0 2px #e5edf9}.timeline article:first-child .timeline-dot{background:var(--blue)}.timeline-meta{display:flex;justify-content:space-between;gap:15px}.timeline-meta h3{font-size:14px}.timeline-meta time{font-size:12px;color:#8f9cb0}.timeline article p{font-size:14px;margin:8px 0;color:#536783;white-space:pre-wrap}.timeline article>span{font-size:12px;color:#8d9bb0}.action-form>h2{font-size:20px}.action-form>p{color:var(--muted);font-size:14px;margin:8px 0 25px}.action-form .form-field{margin-top:20px}.danger-button{background:#be4754;color:white;border-color:#be4754}.danger-button:hover{background:#a43844;color:white}.change-record{border:1px solid var(--border);border-radius:7px;padding:20px;margin-bottom:15px}.change-record>div:first-child{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.change-record .detail-field{margin-bottom:15px}.acceptance-intro h2{font-size:19px}.acceptance-intro>p{font-size:13px;color:var(--muted);margin:7px 0 18px}.acceptance-intro>p span{padding:0 8px}.acceptance-intro .detail-field{margin-top:12px}.deadline{color:#a67a28;font-size:12px;display:flex;align-items:center;gap:8px;padding:12px 0 20px}.acceptance-item{border:1px solid var(--border);border-radius:7px;padding:18px;margin-bottom:13px}.acceptance-item-top{display:flex;align-items:center;gap:12px;margin-bottom:15px}.acceptance-item-top>span{color:var(--blue);font-size:12px}.acceptance-item-top strong{font-size:14px;font-weight:550}.acceptance-item-top select{margin-left:auto;padding:5px 11px;border:1px solid var(--border);border-radius:5px;background:#fff;font-size:13px}.acceptance-item p{display:flex;gap:15px;font-size:14px;margin-top:6px;color:#475c7c}.acceptance-item p>span{font-size:12px;white-space:nowrap;color:#8a98ab;min-width:58px}.acceptance-confirm{margin-top:24px}.acceptance-confirm .check-field{margin:20px 0;font-size:13px;align-items:flex-start}.acceptance-confirm .check-field input{margin-top:4px}.acceptance-record{border-left:3px solid #7fa2d6;padding:16px 20px;margin-top:25px;background:#f7faff;font-size:13px}.acceptance-record h3{font-size:15px;margin-bottom:7px}.acceptance-record p{color:#637896;margin-top:5px}.acceptance-record>span{color:#8c9bb0;font-size:12px;display:block;margin-top:10px}.guide-grid{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:24px}.guide-main{padding:27px}.guide-main>h2{font-size:20px;margin-bottom:15px}.guide-step{display:flex;gap:21px;padding:24px 0;border-bottom:1px solid var(--border)}.guide-step>span{font-size:21px;line-height:1.5;colorLine truncated
@media(max-width:1000px){.guide-grid{grid-template-columns:1fr}.guide-grid>aside{display:grid;grid-template-columns:1fr 1fr;gap:20px}}
@media(max-width:720px){.detail-heading{padding:18px}.detail-title{font-size:20px!important}.detail-description{font-size:11px}.detail-eyeline{gap:8px;font-size:10px}.detail-progress{overflow:auto;padding:16px 18px;gap:18px}.detail-progress>div{flex-direction:column;gap:5px;font-size:10px}.detail-tabs{padding:0 18px;gap:23px}.detail-tabs button{font-size:12px}.detail-content{padding:20px 18px}.detail-overview{grid-template-columns:1fr 1fr;gap:20px}.detail-field p{font-size:13px}.plan-strip>div{grid-template-columns:1fr 1fr}.timeline{padding-left:6px}.timeline-meta{flex-direction:column;gap:2px}.timeline article p{font-size:13px}.modal-footer .text-button{font-size:12px}.acceptance-item{padding:14px}.acceptance-item-top{gap:7px;flex-wrap:wrap}.acceptance-item-top strong{font-size:13px}.acceptance-item p{font-size:12px;gap:9px}.acceptance-item p>span{font-size:11px}.guide-grid>aside{display:block}.guide-main{padding:20px}.guide-main>h2{font-size:18px}.guide-step{gap:14px}.guide-step h3{font-size:15px}.guide-step p{font-size:13px}}
.profile-label{font-size:10px;white-space:nowrap;color:#9aa7bb;margin-left:auto}.guide-active{color:var(--blue)}
@media(min-width:1191px){.status,.priority,.date-cell{font-size:14px}th{font-size:14px}.stats strong{font-size:40px}}
@media(min-width:1450px){td{padding:13px}.tip{padding:15px 0}}
.topbar-right{display:flex;align-items:center;gap:20px}.topbar-right .top-date{display:flex;align-items:center;gap:8px}.account-trigger{display:flex;align-items:center;gap:8px;border:1px solid #e1e8f2;background:#fff;border-radius:7px;padding:6px 10px;font-size:13px;color:#456186}.account-trigger:hover{border-color:#b5cbed;background:#f6f9ff}.account-trigger>span{max-width:130px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.account-dropdown{background:#fff!important;border:1px solid #dfe7f2!important;border-radius:8px!important;min-width:190px!important;box-shadow:0 8px 25px #10224715!important;padding:5px!important;color:#102247}.account-dropdown [data-slot=dropdown-menu-label]{padding:8px 10px!important}.account-dropdown small{display:block;font-size:12px;font-weight:400;color:#8594aa;margin-top:3px}.account-dropdown [data-slot=dropdown-menu-item]{padding:9px 10px!important;font-size:14px!important;cursor:pointer;gap:9px}.account-dropdown [data-highlighted]{background:#eef4ff!important;color:#1762f5}.account-dropdown [data-slot=dropdown-menu-separator]{background:#e7edf5!important}.account-dropdown a{text-decoration:none;color:inherit}
@media(max-width:720px){.topbar-right{gap:8px}.topbar-right .top-date{display:none}.account-trigger{font-size:12px;padding:5px 8px}.account-trigger>span{max-width:85px}}
.form-close-confirm{width:min(440px,calc(100vw - 36px))!important;max-width:440px!important;max-height:calc(100dvh - 36px);overflow:auto;padding:25px!important;background:#fff!important;border:1px solid var(--border)!important;border-radius:12px!important;box-shadow:0 20px 70px #10224730;gap:14px!important;color:var(--ink)}.form-close-confirm [data-slot=alert-dialog-title]{font-size:20px;font-weight:650;line-height:1.5}.form-close-confirm [data-slot=alert-dialog-description]{font-size:14px;line-height:1.85;color:var(--muted)}.form-close-actions{display:flex;justify-content:flex-end;gap:12px;margin-top:9px}.form-close-actions .btn{min-height:42px;flex-shrink:0}
@media(max-width:480px){.form-close-confirm{padding:22px!important}.form-close-actions{gap:10px;flex-wrap:wrap}.form-close-actions .btn{flex:1;font-size:13px;padding:9px 10px}}
.review-solution-note{font-size:13px;line-height:1.8;margin-bottom:18px}
.page-actions{display:flex;gap:10px;align-items:center}.review-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.review-heading h2{font-size:20px}.review-intro{font-size:14px;line-height:1.85;color:var(--muted);margin:12px 0 24px}.review-meta{font-size:13px;line-height:1.8;color:#536783;white-space:pre-wrap;overflow-wrap:anywhere}.review-assignment{padding-bottom:24px;border-bottom:1px solid var(--border)}.review-assignment .review-meta{margin:10px 0}.review-assignment-form{display:grid;gap:16px;margin-top:18px}.review-assignment-form>.btn,.review-editor>.btn{justify-self:start}.review-proposal{padding:24px 0;border-bottom:1px solid var(--border)}.review-proposal h3,.review-editor h3,.review-decision h3{font-size:17px;margin-bottom:18px}.review-proposal .detail-field{margin-bottom:18px}.review-proposal .review-meta{margin-top:8px}.review-invalid{font-size:13px;color:#97521f;line-height:1.8;margin-top:12px;white-space:pre-wrap;overflow-wrap:anywhere}.review-editor,.review-decision{display:grid;gap:18px;padding-top:24px}.review-editor h3,.review-decision h3{margin:0}.review-editor .form-field textarea{min-height:110px}.review-actions{display:flex;justify-content:flex-end;gap:12px}.review-decision .check-field{align-items:flex-start;line-height:1.8}.review-decision .check-field input{margin-top:5px;flex-shrink:0}.review-history{margin-top:28px}.review-history>summary,.review-business-snapshot>summary{cursor:pointer;font-size:14px;color:var(--blue);padding:12px 0}.review-business-snapshot .detail-field{margin-top:12px}.review-panel .error-banner{margin-bottom:18px}.detail-tabs{overflow-x:auto}.detail-tabs button{white-space:nowrap}
@media(max-width:720px){.page-actions{flex-wrap:wrap;justify-content:flex-end;gap:8px}.page-actions .btn{font-size:12px;padding:8px}.review-heading{align-items:flex-start}.review-heading h2{font-size:18px;white-space:nowrap}.review-heading .status{font-size:11px}.review-intro{font-size:13px}.review-actions{flex-wrap:wrap}.review-editor>.btn{width:100%;font-size:13px}.detail-tabs{gap:20px}.detail-tabs button{font-size:12px}}
.attachment-heading{display:flex;justify-content:space-between;gap:12px;font-size:13px;font-weight:600}.attachment-heading>small{font-weight:400;color:#536783}.attachment-help{font-size:12px;line-height:1.8;color:#536783;margin:8px 0 12px}.attachment-input{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.attachment-list{list-style:none;padding:0;margin:14px 0 0;display:grid;gap:10px}.attachment-list>li{display:flex;align-items:center;gap:10px;padding:12px 14px;border:1px solid var(--border);border-radius:7px;min-width:0}.attachment-list>li>svg{flex-shrink:0;color:#536783}.attachment-description{min-width:0;flex:1}.attachment-description>a{font-size:13px;line-height:1.7;color:var(--blue);overflow-wrap:anywhere;text-decoration:underline;text-underline-offset:3px}.attachment-description>small{display:block;font-size:12px;color:#536783;margin-top:3px}.attachment-list .icon-button{flex-shrink:0;width:36px;height:36px}.attachment-progress{display:flex;align-items:center;gap:8px;font-size:13px;color:#365985;margin-top:12px;overflow-wrap:anywhere}.attachment-progress>svg{flex-shrink:0}.attachment-spinner{animation:attachment-spin 1s linear infinite}@keyframes attachment-spin{to{transform:rotate(360deg)}}.attachment-errors{margin-top:12px}.attachment-errors ul{list-style:disc;padding-left:16px;overflow-wrap:anywhere}.attachment-errors li+li{margin-top:7px}.attachment-picker>.btn{margin-top:2px}
@media(prefers-reduced-motion:reduce){.attachment-spinner{animation:none}}
@media(max-width:720px){.attachment-list>li{padding:10px;gap:8px}.attachment-list .icon-button{width:40px;height:40px}.attachment-description>a{font-size:13px}.attachment-help{font-size:12px}}
.attachment-recovery{margin-top:16px}.attachment-recovery>summary{cursor:pointer;font-size:13px;color:var(--blue);padding:8px 0}.attachment-recovery .btn{font-size:12px;padding:6px 10px;flex-shrink:0}
.attachment-recovery-controls{margin-top:14px}.attachment-recovery-controls>.text-button{font-size:12px}.attachment-recovery-controls .error-banner{align-items:flex-start;flex-wrap:wrap}.attachment-recovery-controls .error-banner>span{flex:1 1 220px;overflow-wrap:anywhere}.attachment-recovery-controls .error-banner>.btn{font-size:12px;flex-shrink:0}
.form-field-heading{display:flex;align-items:center;gap:10px 16px;flex-wrap:wrap;min-width:0}.form-field-heading>label{font-weight:600;margin-right:auto}.form-field-heading>label em{margin-left:5px;color:#bd4b57;font-style:normal}.form-field-heading>.text-button{font-size:12px}.template-actions{display:inline-flex;align-items:center;gap:10px 14px;flex-wrap:wrap}.template-actions .text-button{font-size:12px;white-space:nowrap;min-height:30px}.template-actions a[aria-disabled=true]{opacity:.5;pointer-events:none}.contextual-template{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;font-size:13px;color:#536783}.template-modal{width:min(980px,calc(100vw - 48px))!important;z-index:80!important}.template-toolbar{display:flex;gap:10px 18px;align-items:center;flex-wrap:wrap;padding:15px 28px;border-top:1px solid var(--border);border-bottom:1px solid var(--border);flex-shrink:0}.template-toolbar>.btn{font-size:13px}.template-toolbar>.text-button{font-size:13px}.template-scroll{min-height:160px}.template-document{padding:28px 34px 38px;font-size:14px;line-height:1.95;overflow-wrap:anywhere}.template-document h1{font-size:23px;line-height:1.5;margin:0 0 22px}.template-document h2{font-size:20px;margin:30px 0 14px}.template-document h3{font-size:17px;margin:24px 0 12px}.template-document h4{font-size:15px;margin:22px 0 10px}.template-document p{margin:12px 0}.template-document ul,.template-document ol{padding-left:24px;margin:12px 0;list-style:revert}.template-document li{margin:6px 0}.template-document blockquote{margin:16px 0;padding:0 0 0 20px;color:#536783;border-left:1px solid var(--border)}.template-document a,.template-inline-link{color:var(--blue);text-decoration:underline;text-underline-offset:3px}.template-text-block{margin:18px 0;white-space:pre-wrap}.template-text-block code{font-family:inherit;font-size:14px;line-height:2;white-space:pre-wrap}.template-document :not(.template-text-block)>code{font-size:13px}.template-table-wrap{overflow-x:auto;margin:18px 0}.template-table-wrap table{border-collapse:collapse;min-width:560px;width:100%;font-size:13px}.template-table-wrap th,.template-table-wrap td{border:1px solid var(--border);padding:10px 12px;vertical-align:top;white-space:normal;text-align:left;line-height:1.8}.template-table-wrap th{background:#f4f7fb;color:var(--ink);font-weight:600}.template-table-wrap tr:hover{background:transparent}.template-status{padding:32px;margin:0;font-size:14px;color:#536783}.template-status.error-banner{margin:24px}.template-footer{border-top:1px solid var(--border);padding:15px 28px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-shrink:0}.template-footer>p{font-size:12px;color:#536783;line-height:1.7}.template-footer>.btn{flex-shrink:0}.template-library .template-library-intro{font-size:13px;line-height:1.8;color:#536783;margin:-3px 0 16px}.template-library>a.template-directory-link{display:inline-flex;justify-content:center;border:1px solid var(--border);padding:9px 12px;font-size:13px;color:var(--blue);gap:8px}.template-directory-note{display:block;font-size:12px;color:#536783;line-height:1.8;margin:8px 0 18px}.template-library-item{padding:17px 0;border-top:1px solid var(--border)}.template-library-item:last-child{padding-bottom:0}.template-library-item>h3{font-size:14px;font-weight:600;margin-bottom:6px}.template-library-item>p{font-size:12px;line-height:1.8;color:#536783;margin-bottom:8px}.template-library .template-actions a{display:inline-flex;justify-content:initial;padding:0;border:0;color:var(--blue);font-size:12px;gap:6px}.template-library .template-actions a:first-of-type{color:var(--blue)}
.template-table-wrap td:first-child{width:auto}.template-table-wrap th{white-space:nowrap}
@media(max-width:720px){.form-field-heading{gap:6px 12px}.form-field-heading>label{width:100%}.template-actions{gap:8px 14px}.template-actions .text-button{font-size:12px}.template-modal{width:calc(100vw - 20px)!important}.template-toolbar{padding:12px 18px;gap:10px 14px}.template-toolbar>.btn{font-size:12px}.template-toolbar>.text-button{font-size:12px}.template-document{padding:22px 18px 28px;font-size:13px}.template-document h1{font-size:20px}.template-document h2{font-size:18px}.template-document h3{font-size:16px}.template-text-block code{font-size:13px}.template-footer{padding:13px 18px;gap:12px;flex-wrap:wrap}.template-footer>.btn{margin-left:auto;font-size:13px}.contextual-template{align-items:flex-start}}
.admin-readonly-notice{margin-bottom:18px}
@media(max-width:720px){.admin-navigation .brand{flex-shrink:0}.admin-navigation .brand strong{white-space:nowrap}}
@media(max-width:380px){.admin-navigation .brand strong{display:none}.sidebar.admin-navigation{gap:10px}}
/* Delivery workflow follows the existing form and document styles. */
.detail-tabs{overflow-x:auto;flex-shrink:0}.detail-tabs button{flex-shrink:0}
.workflow-heading,.workflow-record-heading{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}.workflow-help{color:#536783;line-height:1.8;margin:12px 0 20px}.workflow-buttons{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0 24px}.workflow-buttons .btn{font-size:13px}.workflow-record{border-top:1px solid var(--border);padding:24px 0}.workflow-record h3{margin-bottom:16px}.workflow-record .detail-field{margin-bottom:16px}.workflow-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px 24px}.workflow-callout{padding:16px 18px;background:#f1f6ff;border:1px solid #d3e2fa;border-radius:7px;margin:16px 0;line-height:1.8}.workflow-callout .workflow-buttons{margin-bottom:0}.workflow-record details{padding:12px 0}.workflow-record summary,.workflow-record>summary{cursor:pointer;font-weight:600;margin-bottom:14px}.workflow-event{padding:12px 0;border-bottom:1px solid var(--border);white-space:pre-wrap;font-size:13px}.workflow-fields{display:grid;gap:20px;border:0;padding:0;margin:20px 0}.workflow-form-actions{display:flex;gap:12px;flex-wrap:wrap;justify-content:flex-end;border-top:1px solid var(--border);padding-top:20px;margin-top:24px}.workflow-leave{flex-basis:100%;background:#fff3eb;padding:16px;border-radius:6px;display:flex;gap:12px;flex-wrap:wrap;align-items:center}.testing-items>h3{margin:12px 0}.testing-item{border:1px solid var(--border);border-radius:6px;padding:16px;margin:16px 0;display:grid;grid-template-columns:1fr 1fr;gap:14px}.testing-item legend{padding:0 8px;font-size:13px}.testing-item .text-button{grid-column:1/-1}.workflow-form .form-field textarea{min-height:80px}.workflow-form .check-field{align-items:flex-start}.workflow-form .check-field input{margin-top:5px}.workflow-due{font-size:12px;color:#a25b16;margin-top:5px}
@media(max-width:720px){.detail-tabs{gap:20px}.workflow-grid,.testing-item{grid-template-columns:1fr}.workflow-buttons .btn{white-space:normal;min-height:40px}.workflow-fields{gap:18px}.workflow-record{padding:20px 0}.workflow-form-actions>.btn{flex:1;white-space:normal}.workflow-leave .btn{white-space:normal}.workflow-record-heading{align-items:flex-start}}
.demand-panel>.tabs{overflow-x:auto}.demand-panel>.tabs button{flex-shrink:0}
+3 -1
View File
@@ -1,4 +1,6 @@
import { appPath } from '@/lib/base-path';
import type { Metadata } from 'next';
import './globals.css';
export const metadata: Metadata={title:'需有序 · 需求登记管理',description:'面向业务方的需求登记、进度跟踪与验收协作平台。',icons:{icon:'/favicon.svg',shortcut:'/favicon.svg'}};
import './account/account.css';
export const metadata: Metadata={title:'需有序 · 需求登记管理',description:'面向业务方的需求登记、进度跟踪与验收协作平台。',icons:{icon:appPath('/favicon.svg'),shortcut:appPath('/favicon.svg')}};
export default function RootLayout({children}:Readonly<{children:React.ReactNode}>){return <html lang="zh-CN"><body>{children}</body></html>}
+37
View File
@@ -0,0 +1,37 @@
import { redirect } from 'next/navigation';
import { LoginForm } from '@/components/account/login-form';
import { getCurrentUser } from '@/lib/server/auth';
import { feishuLoginConfigured } from '@/lib/server/feishu-config';
import { safeReturnTo } from '@/lib/auth-return';
import { feishuErrorMessage } from '@/lib/feishu';
import { appPath } from '@/lib/base-path';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function LoginPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const params = await searchParams;
const next = safeReturnTo(params.next);
const user = await getCurrentUser();
if (user) redirect(user.mustChangePassword ? '/account/password' : next);
const error = feishuErrorMessage(params.feishuError);
const feishuEnabled = feishuLoginConfigured();
return <main className="account-page">
<div className="account-brand brand"><div className="brand-mark" aria-hidden="true"><i /><i /><i /><i /></div><div><strong>需有序</strong><span>需求协作平台</span></div></div>
<section className="account-card" aria-labelledby="login-title">
<h1 id="login-title">登录工作台</h1>
<p className="account-intro">登记需求,跟进进度,让业务协作更有序。</p>
{error && <div className="error-banner" role="alert">{error}</div>}
<LoginForm returnTo={next} />
{feishuEnabled && <div className="feishu-login">
<span className="feishu-divider">或使用飞书</span>
<form action={appPath('/api/auth/feishu/start')} method="post">
<input type="hidden" name="intent" value="login" /><input type="hidden" name="next" value={next} />
<button type="submit" className="btn feishu-login-button">飞书登录</button>
</form>
<p className="account-help">首次飞书登录将自动注册普通成员账号。已有系统账号请先用密码登录并绑定飞书,以保留原有需求。</p>
</div>}
</section>
<p className="account-page-note">{feishuEnabled ? '支持管理员开通的账号,或通过飞书首次登录自动注册。' : '使用本系统账号登录,账号由管理员统一开通。'}</p>
</main>;
}
+9 -2
View File
@@ -1,4 +1,11 @@
import DemandApp from '@/components/demand/app';
import { requireChatGPTUser } from './chatgpt-auth';
import { hasAccountPassword, requireUser } from '@/lib/server/auth';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function Page(){const user=await requireChatGPTUser('/');const today=new Intl.DateTimeFormat('zh-CN',{year:'numeric',month:'long',day:'numeric',timeZone:'Asia/Shanghai'}).format(new Date());return <DemandApp userName={user?.displayName??'业务用户'} today={today}/>}
export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const params = await searchParams;
const demandId = typeof params.demand === 'string' ? params.demand.slice(0, 128) : '';
const user = await requireUser(demandId ? '/?demand=' + encodeURIComponent(demandId) : '/');
const today = new Intl.DateTimeFormat('zh-CN', {year:'numeric',month:'long',day:'numeric',timeZone:'Asia/Shanghai'}).format(new Date());
return <DemandApp userName={user.displayName} role={user.role} today={today} initialDemandId={demandId} passwordSet={hasAccountPassword(user.userId)}/>;
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-230
View File
@@ -1,230 +0,0 @@
// Vendored from @openai/sites-vite-plugin 0.2.0 (openai/sites#9).
// See sites-vite-plugin.LICENSE for the upstream MIT license.
import { access, cp, mkdir, rm } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import { resolve } from "node:path";
import type { Plugin } from "vite";
const localUserId = "local_seedy";
const localEmail = "seedy@sites.test";
const localFullName = "Seedy";
const localCookieName = "__sites_local_auth";
const localHosts = new Set(["localhost", "127.0.0.1", "::1"]);
const localAddresses = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
const authPaths = new Set([
"/signin-with-chatgpt",
"/signout-with-chatgpt",
"/callback",
]);
async function exists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return false;
}
throw error;
}
}
export function sites({ mockAuth = true } = {}): Plugin {
let root = process.cwd();
let command: "build" | "serve" = "build";
return {
name: "sites",
configResolved(config) {
root = config.root;
command = config.command;
},
configureServer(server) {
if (!mockAuth) return;
const secure = Boolean(server.config.server.https);
server.config.logger.info(`Sites local sign-in: ${localEmail}`);
server.middlewares.use((request, response, next) => {
for (const name of Object.keys(request.headers)) {
if (name.startsWith("oai-authenticated-user-")) {
removeHeader(request, name);
}
}
let authority: URL;
let url: URL;
try {
authority = new URL(
`${secure ? "https" : "http"}://${request.headers.host}`,
);
url = new URL(request.url ?? "/", authority);
} catch {
if (authPaths.has((request.url ?? "/").split("?")[0])) {
respond(response, 403);
} else {
next();
}
return;
}
const hostname = authority.hostname
.replace(/^\[|\]$/g, "")
.toLowerCase();
if (
!localHosts.has(hostname) ||
!localAddresses.has(request.socket.remoteAddress ?? "") ||
url.origin !== authority.origin
) {
if (authPaths.has(url.pathname)) respond(response, 403);
else next();
return;
}
const cookies = (request.headers.cookie ?? "")
.split(";")
.map((cookie) => cookie.trim())
.filter(Boolean);
const signInCookies = cookies
.filter((cookie) => cookie.startsWith(`${localCookieName}=`))
.map((cookie) => cookie.slice(localCookieName.length + 1));
const applicationCookies = cookies.filter(
(cookie) => !cookie.startsWith(`${localCookieName}=`),
);
if (applicationCookies.length !== cookies.length) {
removeHeader(request, "cookie");
if (applicationCookies.length) {
setHeader(request, "cookie", applicationCookies.join("; "));
}
}
if (url.pathname === "/callback") {
respond(response, 501);
return;
}
const signIn = url.pathname === "/signin-with-chatgpt";
const signOut = url.pathname === "/signout-with-chatgpt";
if (!signIn && !signOut) {
if (signInCookies.length === 1 && signInCookies[0] === "1") {
setHeader(request, "oai-authenticated-user-id", localUserId);
setHeader(request, "oai-authenticated-user-email", localEmail);
setHeader(
request,
"oai-authenticated-user-full-name",
localFullName,
);
setHeader(
request,
"oai-authenticated-user-full-name-encoding",
"percent-encoded-utf-8",
);
}
next();
return;
}
if (
(request.headers.origin && request.headers.origin !== url.origin) ||
request.headers["sec-fetch-site"] === "cross-site"
) {
respond(response, 403);
return;
}
if (
request.headers["next-router-prefetch"] !== undefined ||
request.headers["x-middleware-prefetch"] === "1" ||
[request.headers.purpose, request.headers["sec-purpose"]].some(
(value) =>
typeof value === "string" &&
value
.split(/[;,]/)
.some((part) => part.trim().toLowerCase() === "prefetch"),
)
) {
respond(response, 204);
return;
}
if (
request.method !== "GET" &&
(!signOut || request.method !== "POST")
) {
response.setHeader("Allow", signIn ? "GET" : "GET, POST");
respond(response, 405);
return;
}
response.statusCode = request.method === "POST" ? 303 : 302;
response.setHeader("Cache-Control", "private, no-store");
response.setHeader(
"Location",
safeReturn(url.searchParams.get("return_to")),
);
response.setHeader(
"Set-Cookie",
`${localCookieName}=${signIn ? "1" : ""}; Path=/; ${
signOut ? "Max-Age=0; " : ""
}HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`,
);
response.end();
});
},
async closeBundle() {
if (command !== "build") return;
const outputDirectory = resolve(root, "dist", ".openai");
const hostingConfig = resolve(root, ".openai", "hosting.json");
const drizzleSource = resolve(root, "drizzle");
await rm(outputDirectory, { recursive: true, force: true });
await mkdir(outputDirectory, { recursive: true });
await cp(hostingConfig, resolve(outputDirectory, "hosting.json"));
if (await exists(drizzleSource)) {
await cp(drizzleSource, resolve(outputDirectory, "drizzle"), {
recursive: true,
});
}
},
};
}
function removeHeader(request: IncomingMessage, name: string): void {
delete request.headers[name];
for (let index = request.rawHeaders.length - 2; index >= 0; index -= 2) {
if (request.rawHeaders[index]?.toLowerCase() === name) {
request.rawHeaders.splice(index, 2);
}
}
}
function setHeader(
request: IncomingMessage,
name: string,
value: string,
): void {
removeHeader(request, name);
request.headers[name] = value;
request.rawHeaders.push(name, value);
}
function respond(response: ServerResponse, status: number): void {
response.statusCode = status;
response.setHeader("Cache-Control", "private, no-store");
response.end();
}
function safeReturn(value: string | null): string {
if (!value?.startsWith("/") || value.startsWith("//")) return "/";
try {
const url = new URL(value, "http://localhost");
if (url.origin !== "http://localhost" || authPaths.has(url.pathname)) {
return "/";
}
return `${url.pathname}${url.search}${url.hash}`;
} catch {
return "/";
}
}
-6
View File
@@ -1,6 +0,0 @@
declare namespace Cloudflare {
interface Env {
DB?: D1Database;
BUCKET?: R2Bucket;
}
}
+45
View File
@@ -0,0 +1,45 @@
'use client';
import { useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { appPath } from '@/lib/base-path';
import type { FeishuBinding } from '@/lib/feishu';
export function FeishuAccount({ binding, configured, passwordSet = true }: { binding: FeishuBinding; configured: boolean; passwordSet?: boolean }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
async function unbind(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const password = new FormData(form).get('password');
setBusy(true); setError(''); setSuccess('');
try {
const response = await fetch(appPath('/api/account/feishu'), { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || '解绑失败,请重试。');
form.reset(); setSuccess('已解除飞书绑定,其他设备的登录已失效。'); router.replace('/account/feishu'); router.refresh();
} catch (cause) { setError(cause instanceof Error ? cause.message : '网络异常,请重试。'); }
finally { setBusy(false); }
}
return <div>
{error && <div className="error-banner" role="alert">{error}</div>}
{success && <div className="account-success" role="status">{success}</div>}
{binding ? <>
<p className="feishu-binding-name">已绑定:<strong>{binding.name}</strong></p>
{!passwordSet ? <>
<p className="account-intro">当前账号通过飞书注册,尚未设置系统密码。请先设置密码,再解除绑定。</p>
<Link className="btn" href="/account/password">设置系统密码</Link>
</> : <>
<p className="account-intro">解除绑定需验证系统密码,其他设备需重新登录。解绑后此飞书身份再次登录会创建新账号;原需求仍可通过当前账号密码访问。</p>
<form className="account-form" onSubmit={unbind} aria-busy={busy}>
<fieldset disabled={busy}><label className="account-field" htmlFor="unbind-password">当前系统密码<input id="unbind-password" name="password" type="password" autoComplete="current-password" required maxLength={128} /></label>
<button className="btn" type="submit">{busy ? '正在解绑…' : '验证密码并解除绑定'}</button></fieldset>
</form>
</>}
</> : configured ? <form action={appPath('/api/auth/feishu/start')} method="post">
<input type="hidden" name="intent" value="bind" /><button type="submit" className="btn primary feishu-login-button">绑定我的飞书账号</button>
</form> : <p className="account-intro">飞书登录尚未配置,请联系管理员完成飞书应用设置。</p>}
</div>;
}
+64
View File
@@ -0,0 +1,64 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { appPath } from '@/lib/base-path';
import type { FeishuDeliveryFilter, FeishuStatus } from '@/lib/feishu';
const deliveryLabels = { pending: '等待发送', sending: '发送中', sent: '已发送', failed: '发送失败' };
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
export function FeishuManagement({ initial }: { initial: FeishuStatus }) {
const [status, setStatus] = useState(initial);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [message, setMessage] = useState('');
const [pageCursors, setPageCursors] = useState<Array<string | null>>([null]);
async function request(action?: 'test' | 'retry', id?: string, selection?: { filter: FeishuDeliveryFilter; cursors: Array<string | null> }) {
setBusy(true); setError(''); setMessage('');
try {
const params = new URLSearchParams({ filter: selection?.filter ?? status.deliveryFilter });
const cursor = (selection?.cursors ?? pageCursors).at(-1);
if (cursor) params.set('cursor', cursor);
const response = await fetch(appPath('/api/admin/feishu?' + params.toString()), action ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, id }) } : { cache: 'no-store' });
const data = await response.json();
if (!response.ok) throw new Error(data.error || '操作失败,请重试。');
setStatus(data); setMessage(action === 'test' ? '测试消息已发送,请在飞书群中查看。' : action === 'retry' ? '已加入发送队列,稍后刷新查看结果。' : '状态已刷新。');
if (selection) setPageCursors(selection.cursors);
} catch (cause) { setError(cause instanceof Error ? cause.message : '网络异常,请重试。'); }
finally { setBusy(false); }
}
return <div className="account-admin-page">
<header className="account-admin-header"><Link className="account-back-link" href="/">返回工作台</Link><strong>需有序</strong></header>
<main className="account-admin-main feishu-admin">
<div className="page-heading"><div><h1>飞书集成</h1><p>管理飞书登录与需求流转群通知。</p></div><button className="btn" disabled={busy} onClick={() => request()}>{busy ? '正在处理…' : '刷新状态'}</button></div>
{error && <div className="error-banner" role="alert">{error}</div>}
{message && <div className="account-success" role="status">{message}</div>}
{status.configurationError && <div className="error-banner" role="alert">{status.configurationError}</div>}
<div className="feishu-settings-grid">
<section className="panel feishu-settings"><h2>飞书登录 <span className="feishu-status">{status.loginConfigured ? '已配置' : '未配置'}</span></h2>
<p>首次飞书登录自动创建普通成员账号,直接进入工作台;已有绑定继续使用原账号的角色和需求。</p>
<dl><dt>授权回调地址</dt><dd><code>{status.callbackUrl}</code></dd><dt>企业限制</dt><dd>{status.tenantRestricted ? '已限制为指定企业' : '按飞书应用可用范围注册及登录'}</dd></dl>
<Link className="text-button" href="/account/feishu">绑定我的飞书账号</Link>
</section>
<section className="panel feishu-settings"><h2>群机器人 <span className="feishu-status">{status.botConfigured ? '已配置' : '未配置'}</span></h2>
<p>正式需求每次成功保存后发送流转摘要,包含标题、状态、操作人和详情链接。草稿不推送。</p>
<p>签名校验:{status.botSigned ? '已配置' : '未配置'}</p>
<button className="btn" disabled={busy || !status.botConfigured} onClick={() => request('test')}>向飞书群发送测试消息</button>
</section>
</div>
<details className="panel feishu-settings"><summary>配置步骤与通知范围</summary>
<ol><li>在飞书开放平台创建企业自建应用,配置网页应用能力,将上方回调地址加入安全设置的重定向 URL,发布应用并设置成员可用范围。</li>
<li>在服务器环境变量配置 FEISHU_APP_ID、FEISHU_APP_SECRET,可用 FEISHU_TENANT_KEY 限定企业。</li>
<li>在目标群添加自定义机器人,配置 FEISHU_BOT_WEBHOOK;开启签名校验时同时配置 FEISHU_BOT_SECRET。关键词校验可填写「需有序」。</li>
<li>重启服务后刷新状态,发送测试消息。密钥仅在服务器设置,无需填写到浏览器。</li></ol>
<p>群成员均可看到通知摘要,请选择适合接收全部正式需求摘要的群。查看详情仍需系统登录及对应权限。发送失败自动重试最多 5 次,之后可手动重试;网络超时可能导致重复消息,可按需求编号和保存版本核对。</p>
</details>
<section className="panel feishu-settings" aria-labelledby="deliveries-title" aria-busy={busy}>
<div className="feishu-delivery-tools"><h2 id="deliveries-title">通知记录</h2><div className="account-field"><label htmlFor="feishu-delivery-filter">通知筛选</label><select id="feishu-delivery-filter" disabled={busy} value={status.deliveryFilter} onChange={event => request(undefined, undefined, { filter: event.target.value as FeishuDeliveryFilter, cursors: [null] })}><option value="all">全部通知</option><option value="failed">发送失败({status.failedCount})</option></select></div></div>
{status.deliveries.length ? <div className="account-users-table-wrap"><table className="account-users-table feishu-deliveries"><thead><tr><th>需求 / 保存版本</th><th>发送状态</th><th>尝试次数</th><th>创建时间</th><th>操作</th></tr></thead>
<tbody>{status.deliveries.map(item => <tr key={item.id}><td><Link href={'/?demand=' + encodeURIComponent(item.demandId)}>{item.demandId}</Link><small>第 {item.revision} 次保存</small></td><td>{deliveryLabels[item.status]}{item.lastError && <small>{item.lastError}</small>}</td><td>{item.attempts}</td><td>{date(item.createdAt)}</td><td>{item.status === 'failed' ? <button className="text-button" disabled={busy} onClick={() => request('retry', item.id)}>重试发送</button> : '—'}</td></tr>)}</tbody></table></div>
: <p className="feishu-empty">{status.deliveryFilter === 'failed' ? '当前页暂无失败通知。可返回上一页或切换为全部通知。' : pageCursors.length > 1 ? '当前页暂无通知,请返回上一页。' : '暂无通知。配置机器人后,新登记及后续流转的正式需求会显示在这里。'}</p>}
<div className="feishu-pagination"><span>第 {pageCursors.length} 页 · 每页最多 50 条{status.failedCount > 0 ? ` · 共有 ${status.failedCount} 条失败通知` : ''}</span><div><button className="btn" disabled={busy || pageCursors.length === 1} onClick={() => request(undefined, undefined, { filter: status.deliveryFilter, cursors: pageCursors.slice(0, -1) })}>上一页</button><button className="btn" disabled={busy || !status.nextCursor} onClick={() => request(undefined, undefined, { filter: status.deliveryFilter, cursors: [...pageCursors, status.nextCursor] })}>下一页</button></div></div>
</section>
</main>
</div>;
}
+50
View File
@@ -0,0 +1,50 @@
'use client';
import { appPath } from '@/lib/base-path';
import { useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowRight, CircleAlert, Eye, EyeOff, LoaderCircle } from 'lucide-react';
export function LoginForm({ returnTo = '/' }: { returnTo?: string }) {
const router = useRouter();
const [visible, setVisible] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const fields = new FormData(event.currentTarget);
setBusy(true);
setError('');
try {
const response = await fetch(appPath('/api/auth/login'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: String(fields.get('username')).trim(), password: fields.get('password') }),
});
const data = await response.json() as { error?: string; user?: { mustChangePassword: boolean } };
if (!response.ok || !data.user) throw new Error(data.error || '暂时无法登录,请稍后重试。');
router.replace(data.user.mustChangePassword ? '/account/password' : returnTo);
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
setBusy(false);
}
}
return <form className="account-form" onSubmit={submit} aria-busy={busy}>
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy}>
<label className="account-field" htmlFor="username">账号
<input id="username" name="username" autoComplete="username" autoCapitalize="none" spellCheck={false} required maxLength={64} placeholder="请输入管理员分配的账号" autoFocus />
</label>
<label className="account-field" htmlFor="password">密码</label>
<div className="account-password-input">
<input id="password" name="password" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} placeholder="请输入密码" />
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏密码' : '显示密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
</div>
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在登录…</> : <>登录工作台<ArrowRight size={18} /></>}</button>
</fieldset>
<p className="account-help">需要开通账号或忘记密码,请联系系统管理员。</p>
</form>;
}
+82
View File
@@ -0,0 +1,82 @@
'use client';
import { appPath } from '@/lib/base-path';
import { useState, type FormEvent } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft, CircleAlert, Eye, EyeOff, Info, LoaderCircle, LogOut } from 'lucide-react';
export function PasswordForm({ username, mustChangePassword, passwordSet = true }: { username: string; mustChangePassword: boolean; passwordSet?: boolean }) {
const router = useRouter();
const [visible, setVisible] = useState(false);
const [busy, setBusy] = useState(false);
const [leaving, setLeaving] = useState(false);
const [error, setError] = useState('');
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const fields = new FormData(event.currentTarget);
setError('');
if (fields.get('newPassword') !== fields.get('confirmation')) {
setError('两次输入的新密码不一致,请重新确认。');
event.currentTarget.querySelector<HTMLInputElement>('#confirmation')?.focus();
return;
}
setBusy(true);
try {
const response = await fetch(appPath('/api/auth/password'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...(passwordSet ? { currentPassword: fields.get('currentPassword') } : {}), newPassword: fields.get('newPassword') }),
});
const data = await response.json() as { error?: string };
if (!response.ok) throw new Error(data.error || '修改失败,请稍后重试。');
router.replace('/');
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
setBusy(false);
}
}
async function logout() {
setLeaving(true);
setError('');
try {
const response = await fetch(appPath('/api/auth/logout'), { method: 'POST' });
if (!response.ok) throw new Error('退出登录失败,请重试。');
router.replace('/login');
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '退出登录失败,请重试。');
setLeaving(false);
}
}
return <>
{!passwordSet && <div className="info-banner account-password-notice"><Info size={18} /><span>你当前通过飞书登录。设置系统密码后,也可使用上方账号和密码登录。</span></div>}
{mustChangePassword && <div className="info-banner account-password-notice"><Info size={18} /><span>请将管理员分配的临时密码改为自己的密码,完成后即可进入工作台。</span></div>}
<form className="account-form" onSubmit={submit} aria-busy={busy}>
<input type="text" name="username" value={username} autoComplete="username" readOnly hidden />
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy || leaving}>
{passwordSet && <label className="account-field" htmlFor="currentPassword">{mustChangePassword ? '临时密码' : '当前密码'}
<input id="currentPassword" name="currentPassword" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} autoFocus />
</label>}
<div className="account-field"><label htmlFor="newPassword">新密码</label>
<input id="newPassword" name="newPassword" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="password-guidance" autoFocus={!passwordSet} />
<small id="password-guidance">12–128 个字符,可使用方便记忆的长密码。</small>
</div>
<label className="account-field" htmlFor="confirmation">确认新密码
<input id="confirmation" name="confirmation" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} />
</label>
<button className="text-button account-show-password" type="button" onClick={() => setVisible(!visible)} aria-pressed={visible}>{visible ? <EyeOff size={17} /> : <Eye size={17} />}{visible ? '隐藏密码' : '显示密码'}</button>
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在保存…</> : '保存密码并进入工作台'}</button>
</fieldset>
</form>
<div className="account-form-footer">
{!mustChangePassword && <Link href="/" className="text-button"><ArrowLeft size={16} />返回工作台</Link>}
<button className="text-button" onClick={logout} disabled={busy || leaving}><LogOut size={16} />{leaving ? '正在退出…' : '退出登录'}</button>
</div>
</>;
}
+140
View File
@@ -0,0 +1,140 @@
'use client';
import { appPath } from '@/lib/base-path';
import { useCallback, useEffect, useState, type FormEvent } from 'react';
import Link from 'next/link';
import { ArrowLeft, CheckCircle2, CircleAlert, Eye, EyeOff, KeyRound, LoaderCircle, Plus, RotateCw, Search, ShieldCheck, UserRound, UsersRound, X } from 'lucide-react';
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import type { AdminUser } from '@/lib/server/auth';
type AccountAction = { kind: 'create' } | { kind: 'reset-password' | 'disable' | 'enable'; user: AdminUser };
async function readResponse(response: Response) {
const data = await response.json() as { error?: string; users?: AdminUser[] };
if (!response.ok) throw new Error(data.error || '操作失败,请稍后重试。');
return data;
}
function AccountDialog({ action, onClose, onSaved }: { action: AccountAction; onClose: () => void; onSaved: (message: string) => void }) {
const [busy, setBusy] = useState(false);
const [visible, setVisible] = useState(false);
const [error, setError] = useState('');
const creating = action.kind === 'create';
const settingPassword = creating || action.kind === 'reset-password';
const title = creating ? '开通账号' : action.kind === 'reset-password' ? '重置密码' : action.kind === 'disable' ? '停用账号' : '启用账号';
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const fields = new FormData(event.currentTarget);
setBusy(true);
setError('');
try {
const body = action.kind === 'create'
? { username: String(fields.get('username')).trim(), displayName: String(fields.get('displayName')).trim(), password: fields.get('password'), role: fields.get('role') }
: { id: action.user.userId, action: action.kind, ...(settingPassword ? { password: fields.get('password') } : {}) };
await readResponse(await fetch(appPath('/api/admin/users'), {
method: creating ? 'POST' : 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}));
const name = action.kind === 'create' ? String(fields.get('displayName')).trim() : action.user.displayName;
onSaved(action.kind === 'create' ? `已为 ${name} 开通账号,请将账号和临时密码告知本人。` : action.kind === 'reset-password' ? `已重置 ${name} 的密码,下次登录时需要设置新密码。` : `已${action.kind === 'disable' ? '停用' : '启用'} ${name} 的账号。`);
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
setBusy(false);
}
}
return <Dialog open onOpenChange={open => { if (!open && !busy) onClose(); }}>
<DialogContent className="account-dialog" showCloseButton={false} onEscapeKeyDown={event => { if (busy) event.preventDefault(); }} onPointerDownOutside={event => { if (busy) event.preventDefault(); }}>
<div className="account-dialog-heading"><DialogTitle>{title}</DialogTitle><DialogClose asChild><button type="button" className="account-icon-button" aria-label="关闭" disabled={busy}><X size={20} /></button></DialogClose></div>
<DialogDescription className="account-dialog-description">{creating ? '为指定用户创建账号,首次登录后由用户设置自己的密码。' : action.kind === 'reset-password' ? `为 ${action.user.displayName}(${action.user.username})设置新的临时密码,原有登录将失效。` : action.kind === 'disable' ? `停用后,${action.user.displayName} 将退出登录且无法再次登录。已登记的需求会保留。` : `启用后,${action.user.displayName} 可继续使用原账号和密码登录。`}</DialogDescription>
<form className="account-form" onSubmit={submit} aria-busy={busy}>
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy}>
{creating && <>
<label className="account-field" htmlFor="new-username">登录账号
<input id="new-username" name="username" autoComplete="off" autoCapitalize="none" spellCheck={false} required minLength={3} maxLength={64} pattern="[a-zA-Z0-9][a-zA-Z0-9._@\-]{2,63}" aria-describedby="username-guidance" placeholder="例如 zhangsan" />
<small id="username-guidance">3–64 位,以字母或数字开头,可包含 . _ @ -;不区分大小写。</small>
</label>
<label className="account-field" htmlFor="new-displayName">用户姓名
<input id="new-displayName" name="displayName" autoComplete="off" required maxLength={80} placeholder="例如 张三" />
</label>
<label className="account-field" htmlFor="new-role">账号角色
<select id="new-role" name="role" defaultValue="user"><option value="user">业务用户</option><option value="admin">管理员</option></select>
<small>管理员可以开通、停用账号和重置密码。</small>
</label>
</>}
{settingPassword && <>
<label className="account-field" htmlFor="new-account-password">临时密码</label>
<div className="account-password-input">
<input id="new-account-password" name="password" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="temporary-password-guidance" />
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏临时密码' : '显示临时密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
</div>
<small className="account-field-hint" id="temporary-password-guidance">12–128 个字符。请保存并告知用户,关闭后无法查看。</small>
</>}
<div className="account-dialog-actions"><button type="button" className="btn" onClick={onClose}>取消</button><button className={`btn ${action.kind === 'disable' ? 'danger-button' : 'primary'}`} type="submit">{busy ? <><LoaderCircle className="account-spinner" size={17} />正在保存…</> : title}</button></div>
</fieldset>
</form>
</DialogContent>
</Dialog>;
}
export function UserManagement({ currentUserId }: { currentUserId: string }) {
const [users, setUsers] = useState<AdminUser[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [query, setQuery] = useState('');
const [action, setAction] = useState<AccountAction | null>(null);
const [message, setMessage] = useState('');
const load = useCallback((signal?: AbortSignal) => fetch(appPath('/api/admin/users'), { cache: 'no-store', signal })
.then(readResponse)
.then(data => {
if (!signal?.aborted) { setUsers(data.users || []); setError(''); }
}).catch(cause => {
if (!signal?.aborted) setError(cause instanceof Error ? cause.message : '无法加载账号,请重试。');
}).finally(() => {
if (!signal?.aborted) setLoading(false);
}), []);
useEffect(() => {
const controller = new AbortController();
void load(controller.signal);
return () => controller.abort();
}, [load]);
const search = query.trim().toLocaleLowerCase();
const matching = users.filter(user => `${user.username} ${user.displayName}`.toLocaleLowerCase().includes(search));
function reload() {
setLoading(true);
void load();
}
function saved(text: string) {
setAction(null);
setMessage(text);
reload();
}
return <div className="account-admin-page">
<header className="account-admin-header"><Link className="account-back-link" href="/"><ArrowLeft size={18} />返回工作台</Link><div className="account-admin-brand"><div className="brand-mark" aria-hidden="true"><i /><i /><i /><i /></div><strong>需有序</strong></div></header>
<main className="account-admin-main">
<div className="page-heading"><div><h1>账号管理</h1><p>为指定用户开通访问权限,统一管理账号状态。</p></div><button className="btn primary" onClick={() => { setMessage(''); setAction({ kind: 'create' }); }}><Plus size={18} />开通账号</button></div>
<div className="info-banner account-admin-note"><ShieldCheck size={19} /><p>仅已开通且处于启用状态的账号可以登录。每位用户只能查看和管理自己登记的需求。</p></div>
{message && <div className="account-success" role="status"><CheckCircle2 size={18} /><span>{message}</span><button className="account-icon-button" aria-label="关闭操作提示" onClick={() => setMessage('')}><X size={18} /></button></div>}
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span><button className="text-button" onClick={reload} disabled={loading}>重新加载</button></div>}
<section className="panel account-users-panel" aria-labelledby="users-list-heading" aria-busy={loading}>
<div className="account-users-toolbar"><div className="account-users-title"><UsersRound size={19} /><h2 id="users-list-heading">全部账号</h2><span>{users.length}</span></div><div className="account-users-tools"><label className="search-field"><Search size={17} /><input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="搜索账号或姓名" aria-label="搜索账号或姓名" /></label><button className="account-icon-button" onClick={reload} disabled={loading} aria-label="刷新账号列表"><RotateCw size={18} className={loading ? 'account-spinner' : ''} /></button></div></div>
<div className="account-users-table-wrap"><table className="account-users-table"><thead><tr><th scope="col">用户</th><th scope="col">角色</th><th scope="col">状态</th><th scope="col">最近登录</th><th scope="col">操作</th></tr></thead><tbody>
{matching.map(user => <tr key={user.userId}><td><div className="account-user-identity"><span className="avatar"><UserRound size={19} /></span><div><strong>{user.displayName}{user.userId === currentUserId && <span className="account-self">我</span>}</strong><span>{user.username}</span></div></div></td><td><span className={user.role === 'admin' ? 'account-role-admin' : ''}>{user.role === 'admin' ? '管理员' : '业务用户'}</span></td><td><span className={`status ${user.disabled ? 'gray' : 'green'}`}>{user.disabled ? '已停用' : '已启用'}</span>{user.mustChangePassword && !user.disabled && <small className="account-password-pending">待设置密码</small>}</td><td className="account-login-date">{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }) : '尚未登录'}</td><td><div className="account-row-actions">{user.userId === currentUserId ? <a className="text-button" href={appPath('/account/password')}><KeyRound size={15} />修改密码</a> : <><button className="text-button" onClick={() => setAction({ kind: 'reset-password', user })}>重置密码</button><button className={`text-button ${user.disabled ? '' : 'danger-text'}`} onClick={() => setAction({ kind: user.disabled ? 'enable' : 'disable', user })}>{user.disabled ? '启用' : '停用'}</button></>}</div></td></tr>)}
</tbody></table></div>
{loading && users.length === 0 && <div className="account-list-empty" role="status"><LoaderCircle className="account-spinner" size={24} /><p>正在加载账号…</p></div>}
{!loading && !matching.length && <div className="account-list-empty"><UsersRound size={28} /><h3>{query ? '没有找到匹配的账号' : error ? '账号列表暂不可用' : '暂无账号'}</h3><p>{query ? '试试其他账号或姓名。' : error ? '请重新加载后再试。' : '点击“开通账号”为指定用户添加访问权限。'}</p></div>}
<div className="account-users-footer">{search ? `找到 ${matching.length} 个账号` : `共 ${users.length} 个账号,${users.filter(user => !user.disabled).length} 个已启用`}<span>停用账号会保留已登记的需求</span></div>
</section>
</main>
{action && <AccountDialog action={action} onClose={() => setAction(null)} onSaved={saved} />}
</div>;
}
+40 -23
View File
@@ -1,36 +1,53 @@
'use client';
import { appPath } from '@/lib/base-path';
import { useState, useEffect, useRef, useCallback } from 'react';
import { House, Files, SquareCheck, Folder, BookOpen, CalendarDays, ChevronRight, UserRound, CheckCircle2, CircleAlert, RotateCw } from 'lucide-react';
import { House, Files, SquareCheck, Folder, BookOpen, CalendarDays, ChevronRight, UserRound, CheckCircle2, CircleAlert, RotateCw, LogOut, KeyRound, UsersRound, ClipboardList } from 'lucide-react';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu';
import { Dashboard } from './dashboard';
import { DemandForm, type SaveInput } from './form';
import { DemandDetail } from './detail';
import { Guide } from './guide';
import { demoDemands } from '@/lib/demo';
import { type Demand, needsAction } from '@/lib/demand';
import { type Demand, needsAction, isMyDemand } from '@/lib/demand';
import { mergeDemandSnapshot, type SavedDemandWrite } from '@/lib/demand-snapshot';
const navItems=[{icon:House,label:'我的工作台'},{icon:Files,label:'我的需求'},{icon:SquareCheck,label:'待我处理'},{icon:Folder,label:'草稿箱'}];
export default function DemandApp({userName,today}:{userName:string;today:string}){
const [view,setView]=useState('我的工作台');const [actual,setActual]=useState<Demand[]>([]);const [examples,setExamples]=useState<Demand[]>(demoDemands);const [demo,setDemo]=useState(true);const [loading,setLoading]=useState(true);const [loadError,setLoadError]=useState('');const [actionError,setActionError]=useState('');const [busy,setBusy]=useState(false);const [toast,setToast]=useState('');const [selected,setSelected]=useState<Demand|null>(null);const [form,setForm]=useState<{initial?:Demand}|null>(null);const [dashboardKey,setDashboardKey]=useState(0);
const demands=demo?examples:actual;const latest=useRef(demands);latest.current=demands;
const load=useCallback(async()=>{setLoading(true);setLoadError('');try{const response=await fetch('/api/demands',{cache:'no-store'});const data=await response.json() as {error?:string;demands:Demand[]};if(!response.ok)throw new Error(data.error);setActual(data.demands);if(data.demands.length)setDemo(false);}catch(e){setLoadError(e instanceof Error?e.message:'无法加载需求,请重试。');}finally{setLoading(false)}},[]);
useEffect(()=>{void load()},[load]);
export default function DemandApp({userName,role,today,initialDemandId='',passwordSet=true}:{passwordSet?:boolean;initialDemandId?:string;userName:string;role:'admin'|'user';today:string}){
const [signingOut,setSigningOut]=useState(false);const [view,setView]=useState('我的工作台');const [demands,setDemands]=useState<Demand[]>([]);const [loading,setLoading]=useState(true);const [loadError,setLoadError]=useState('');const [actionError,setActionError]=useState('');const [busy,setBusy]=useState(false);const [toast,setToast]=useState('');const [selected,setSelected]=useState<Demand|null>(null);const [form,setForm]=useState<{initial?:Demand}|null>(null);const [dashboardKey,setDashboardKey]=useState(0);
const [detailTab,setDetailTab]=useState<string|undefined>();
const personalDemands=demands.filter(isMyDemand);
const dashboardDemands=view==='全部需求'&&role==='admin'?demands.filter(d=>d.status!=='草稿'):personalDemands;
const navigation=role==='admin'?[...navItems.slice(0,2),{icon:ClipboardList,label:'全部需求'},...navItems.slice(2)]:navItems;
const initialDemand=useRef(initialDemandId);
const latest=useRef(demands);useEffect(()=>{latest.current=demands},[demands]);
const mounted=useRef(false);const loadSequence=useRef(0);const loadController=useRef<AbortController|null>(null);
const writeVersion=useRef(0);const savedWrites=useRef(new Map<string,SavedDemandWrite>());
const load=useCallback(()=>{
const sequence=++loadSequence.current;const startedAtVersion=writeVersion.current;
loadController.current?.abort();const controller=new AbortController();loadController.current=controller;
const current=()=>mounted.current&&sequence===loadSequence.current&&!controller.signal.aborted;
return fetch(appPath('/api/demands'),{cache:'no-store',signal:controller.signal})
.then(async response=>{const data=await response.json() as {error?:string;demands:Demand[]};if(!response.ok)throw new Error(data.error||'无法加载需求,请重试。');return data.demands;})
.then(snapshot=>{if(!current())return;setDemands(mergeDemandSnapshot(snapshot,savedWrites.current.values(),startedAtVersion));setLoadError('');
if(initialDemand.current){const requested=snapshot.find(d=>d.id===initialDemand.current);initialDemand.current='';if(requested){setSelected(requested);setDetailTab(undefined);}else setLoadError('找不到通知对应的需求,或当前账号没有查看权限。');}
for(const [id,write] of savedWrites.current){if(write.version<=startedAtVersion)savedWrites.current.delete(id);}
})
.catch(error=>{if(current())setLoadError(error instanceof Error?error.message:'无法加载需求,请重试。');})
.finally(()=>{if(current()){setLoading(false);loadController.current=null;}});
},[]);
function reload(){setLoading(true);setLoadError('');void load();}
useEffect(()=>{mounted.current=true;void load();return()=>{mounted.current=false;loadController.current?.abort();};},[load]);
useEffect(()=>{if(!toast)return;const t=setTimeout(()=>setToast(''),4500);return()=>clearTimeout(t)},[toast]);
useEffect(()=>{const mc=(document as unknown as {modelContext?:{registerTool:(tool:unknown,options:unknown)=>Promise<void>|void}}).modelContext;if(!mc?.registerTool)return;const lifecycle=new AbortController();const tools=[{name:'search_demands',title:'搜索当前工作空间需求',description:'Read demands currently visible in this workspace, including explicit demo flags. Does not change records.',inputSchema:{type:'object',properties:{query:{type:'string'}},required:['query'],additionalProperties:false},annotations:{readOnlyHint:true,untrustedContentHint:true},execute(input:unknown){if(!input||typeof (input as {query:unknown}).query!=='string')throw new Error('query must be a string');const query=(input as {query:string}).query.toLowerCase();return latest.current.filter(d=>(d.id+d.fields.title).toLowerCase().includes(query)).map(d=>({id:d.id,title:d.fields.title,status:d.status,demo:!!d.demo}));}},{name:'start_demand_registration',title:'打开需求登记表',description:'Open the registration form. This does not save or submit a demand.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:false,untrustedContentHint:false},execute(input:unknown){if(!input||typeof input!=='object'||Object.keys(input).length)throw new Error('Expected an empty object');setActionError('');setForm({});return {opened:true,saved:false};}}];for(const tool of tools){try{Promise.resolve(mc.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{})}catch{}}return()=>lifecycle.abort()},[]);
useEffect(()=>{const mc=(document as unknown as {modelContext?:{registerTool:(tool:unknown,options:unknown)=>Promise<void>|void}}).modelContext;if(!mc?.registerTool)return;const lifecycle=new AbortController();const tools=[{name:'search_demands',title:'搜索当前工作空间需求',description:'Read saved demands currently visible in this workspace. Does not change records.',inputSchema:{type:'object',properties:{query:{type:'string'}},required:['query'],additionalProperties:false},annotations:{readOnlyHint:true,untrustedContentHint:true},execute(input:unknown){if(!input||typeof (input as {query:unknown}).query!=='string')throw new Error('query must be a string');const query=(input as {query:string}).query.toLowerCase();return latest.current.filter(d=>(d.id+d.fields.title).toLowerCase().includes(query)).map(d=>({id:d.id,title:d.fields.title,status:d.status}));}},{name:'start_demand_registration',title:'打开需求登记表',description:'Open the registration form. This does not save or submit a demand.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:false,untrustedContentHint:false},execute(input:unknown){if(!input||typeof input!=='object'||Object.keys(input).length)throw new Error('Expected an empty object');setActionError('');setForm({});return {opened:true,saved:false};}}];for(const tool of tools){try{Promise.resolve(mc.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{})}catch{}}return()=>lifecycle.abort()},[]);
function navigate(v:string){setView(v);setDashboardKey(k=>k+1);setSelected(null);setActionError('')}
function startNew(){setActionError('');setForm({})}
async function save(body:SaveInput){setBusy(true);setActionError('');try{const response=await fetch('/api/demands',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await response.json() as {error?:string;demand:Demand};if(!response.ok)throw new Error(data.error||'保存失败,请稍后重试。');const updated=data.demand as Demand;setActual(prev=>[updated,...prev.filter(d=>d.id!==updated.id)]);setDemo(false);setForm(null);setSelected(updated);setToast(body.mode==='draft'?'草稿已保存,可随时继续填写':body.mode==='review'?'需求已提交评审,等待负责人确认':'需求已保存');setView(updated.status==='草稿'?'草稿箱':'我的需求');setDashboardKey(k=>k+1);return;}catch(e){setActionError(e instanceof Error?e.message:'保存失败,请重试。');throw e;}finally{setBusy(false)}}
async function action(body:SaveInput){setActionError('');if(!selected)return;if(!selected.demo){await save(body);return;}
const now=new Date().toISOString();const next=structuredClone(selected);next.revision++;next.updatedAt=now;let label='';let detail='';
if(body.action==='cancel'){next.status='已取消';label='取消需求';detail=String(body.reason)}
if(body.action==='change'){next.changes.push({time:now,actor:'业务用户(示例)',content:String(body.content),reason:String(body.reason),status:'待开发评估与双方确认',originalVersion:next.fields.version,originalFields:structuredClone(next.fields)});label='提出需求变更';detail=String(body.content)+';原因:'+String(body.reason)}
if(body.action==='accept'){const results=body.results as string[];if(!next.acceptance||results.some(r=>!['通过','不通过'].includes(r))||!body.confirm||!String(body.notes).trim()){setActionError('请完成清单并确认结论。');return;}const passed=results.every(r=>r==='通过');next.status=passed?'待发布':'开发中';next.acceptanceRecords??=[];next.acceptanceRecords.push({time:now,actor:'业务用户(示例)',version:next.fields.version,testVersion:next.acceptance.testVersion,results,notes:String(body.notes),passed,items:next.acceptance.items.map((item,i)=>({...item,result:results[i]})),environment:next.acceptance.environment});label=passed?'业务验收通过':'业务验收未通过';detail=String(body.notes)}
next.history.push({time:now,actor:'业务用户(示例)',action:label,detail});setExamples(prev=>prev.map(d=>d.id===next.id?next:d));setSelected(next);setToast('示例操作完成:'+label);
}
return <div className="app-shell">{loading&&<div className="loading-bar" role="progressbar" aria-label="正在加载需求"/>}<aside className="sidebar"><div className="brand"><div className="brand-mark"><i/><i/><i/><i/></div><div><strong>需有序</strong><span>需求协作平台</span></div></div><nav aria-label="主导航">{navItems.map(({icon:Icon,label})=><button key={label} title={label} aria-label={label} className={view===label?'active':''} onClick={()=>navigate(label)}><Icon size={21}/><span>{label}</span>{label==='待我处理'&&demands.filter(needsAction).length>0&&<b className="nav-count alert">{demands.filter(needsAction).length}</b>}{label==='草稿箱'&&demands.filter(d=>d.status==='草稿').length>0&&<b className="nav-count">{demands.filter(d=>d.status==='草稿').length}</b>}</button>)}</nav><div className="sidebar-bottom"><button className={'guide-nav '+(view==='流程与规范'?'guide-active':'')} onClick={()=>navigate('流程与规范')}><BookOpen size={21}/>流程与规范</button><div className="profile" title={userName}><span className="avatar"><UserRound size={21}/></span><strong>{demo?'业务用户':userName}</strong><span className="profile-label">业务方</span></div></div></aside><div className="main-shell"><header className="topbar"><span>工作空间<ChevronRight size={14}/><strong>{view}</strong></span><span className="top-date"><CalendarDays size={17}/>{today}</span></header><main>
{loadError&&<div className="error-banner page-error" role="alert"><CircleAlert size={18}/><span>{loadError}{demo?' 当前展示示例数据。':''}</span><button className="text-button" onClick={load}><RotateCw size={14}/>重新加载</button></div>}
{view==='流程与规范'?<Guide onNew={startNew}/>:<Dashboard key={dashboardKey} demands={demands} view={view} onView={setView} onOpen={d=>{setSelected(d);setActionError('')}} onNew={startNew} onGuide={()=>navigate('流程与规范')} demo={demo} onMode={()=>{setDemo(!demo);setDashboardKey(k=>k+1)}}/>}
function startNew(){setActionError('');setDetailTab(undefined);setForm({})}
async function signOut(){setSigningOut(true);try{const response=await fetch(appPath('/api/auth/logout'),{method:'POST'});if(!response.ok)throw new Error('退出登录失败,请重试。');window.location.assign(appPath('/login'));}catch(e){setLoadError(e instanceof Error?e.message:'退出登录失败。');setSigningOut(false)}}
async function save(body:SaveInput){setBusy(true);setActionError('');try{const response=await fetch(appPath('/api/demands'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await response.json() as {error?:string;demand:Demand};if(!response.ok)throw new Error(data.error||'保存失败,请稍后重试。');if(!mounted.current)return;const updated=data.demand as Demand;savedWrites.current.set(updated.id,{version:++writeVersion.current,demand:updated});setDemands(prev=>[updated,...prev.filter(d=>d.id!==updated.id)]);setForm(null);setSelected(updated);setToast(body.action==='take-over-development'?'已接手开发职责,请重新评审和排期':body.action==='assign-developer'?'开发责任人已指定':body.action==='propose-solution'?'方案已提交,等待业务方确认':body.action==='confirm-solution'?'方案已确认,确认记录已保存':body.action==='return-solution'?'已退回开发责任人修改':body.mode==='draft'?'草稿已保存,可随时继续填写':body.mode==='review'?'需求已提交评审,等待负责人确认':'需求已保存');setView(updated.status==='草稿'?'草稿箱':'我的需求');setDashboardKey(k=>k+1);return;}catch(e){if(mounted.current)setActionError(e instanceof Error?e.message:'保存失败,请重试。');throw e;}finally{if(mounted.current)setBusy(false)}}
async function action(body:SaveInput){if(!selected)return;await save(body)}
return <div className="app-shell">{loading&&<div className="loading-bar" role="progressbar" aria-label="正在加载需求"/>}<aside className={'sidebar'+(role==='admin'?' admin-navigation':'')}><div className="brand"><div className="brand-mark"><i/><i/><i/><i/></div><div><strong>需有序</strong><span>需求协作平台</span></div></div><nav aria-label="主导航">{navigation.map(({icon:Icon,label})=><button key={label} title={label} aria-label={label} className={view===label?'active':''} onClick={()=>navigate(label)}><Icon size={21}/><span>{label}</span>{label==='待我处理'&&personalDemands.filter(needsAction).length>0&&<b className="nav-count alert">{personalDemands.filter(needsAction).length}</b>}{label==='草稿箱'&&personalDemands.filter(d=>d.status==='草稿').length>0&&<b className="nav-count">{personalDemands.filter(d=>d.status==='草稿').length}</b>}</button>)}</nav><div className="sidebar-bottom"><button className={'guide-nav '+(view==='流程与规范'?'guide-active':'')} onClick={()=>navigate('流程与规范')}><BookOpen size={21}/>流程与规范</button><div className="profile" title={userName}><span className="avatar"><UserRound size={21}/></span><strong>{userName}</strong><span className="profile-label">{role==='admin'?'管理员':'成员'}</span></div></div></aside><div className="main-shell"><header className="topbar"><span>工作空间<ChevronRight size={14}/><strong>{view}</strong></span><div className="topbar-right"><span className="top-date"><CalendarDays size={17}/>{today}</span><DropdownMenu><DropdownMenuTrigger asChild><button className="account-trigger" aria-label="账号菜单"><UserRound size={18}/><span>{userName}</span></button></DropdownMenuTrigger><DropdownMenuContent className="account-dropdown" align="end"><DropdownMenuLabel>{userName}<small>{role==='admin'?'系统管理员':'协作成员'}</small></DropdownMenuLabel><DropdownMenuSeparator/>{role==='admin'&&<DropdownMenuItem asChild><a href={appPath('/admin/users')}><UsersRound size={16}/>账号管理</a></DropdownMenuItem>}{role==='admin'&&<DropdownMenuItem asChild><a href={appPath('/admin/feishu')}><UsersRound size={16}/>飞书集成</a></DropdownMenuItem>}<DropdownMenuItem asChild><a href={appPath('/account/feishu')}><UserRound size={16}/>飞书绑定</a></DropdownMenuItem><DropdownMenuItem asChild><a href={appPath('/account/password')}><KeyRound size={16}/>{passwordSet?'修改密码':'设置密码'}</a></DropdownMenuItem><DropdownMenuSeparator/><DropdownMenuItem disabled={signingOut} onClick={signOut}><LogOut size={16}/>{signingOut?'正在退出…':'退出登录'}</DropdownMenuItem></DropdownMenuContent></DropdownMenu></div></header><main>
{loadError&&<div className="error-banner page-error" role="alert"><CircleAlert size={18}/><span>{loadError}</span><button className="text-button" onClick={reload} disabled={loading}><RotateCw size={14}/>重新加载</button></div>}
{view==='流程与规范'?<Guide onNew={startNew}/>:<Dashboard key={dashboardKey} demands={dashboardDemands} view={view} onView={setView} onOpen={d=>{setSelected(d);setDetailTab(undefined);setActionError('')}} onNew={startNew} onGuide={()=>navigate('流程与规范')} onRefresh={reload} loading={loading} unavailable={Boolean(loadError)}/>}
</main></div>
{selected&&!form&&<DemandDetail key={selected.id+'-'+selected.revision} d={selected} onClose={()=>setSelected(null)} onEdit={d=>{setForm({initial:d});setActionError('')}} onAction={action} busy={busy} error={actionError}/>}
{form&&<DemandForm initial={form.initial} onSave={async body=>{try{await save(body)}catch{}}} onClose={()=>setForm(null)} busy={busy} error={actionError} userName={userName==='seedy@sites.test'?'业务用户':userName} existing={actual}/>}
{selected&&!form&&<DemandDetail key={selected.id+'-'+selected.revision} d={selected} initialTab={detailTab} onTabChange={setDetailTab} onClose={()=>setSelected(null)} onEdit={d=>{setForm({initial:d});setActionError('')}} onAction={action} busy={busy} error={actionError}/>}
{form&&<DemandForm initial={form.initial} onSave={async body=>{try{await save(body)}catch{}}} onClose={()=>setForm(null)} busy={busy} error={actionError} userName={userName} existing={personalDemands.filter(d=>d.access?.business??true)}/>}
{toast&&<div className="toast" role="status"><CheckCircle2 size={18}/>{toast}</div>}
</div>;
}
+127
View File
@@ -0,0 +1,127 @@
'use client';
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
import { Download, FileText, LoaderCircle, Paperclip, RotateCw, X } from 'lucide-react';
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, formatFileSize, type Attachment } from '@/lib/attachments';
import { appPath } from '@/lib/base-path';
export function AttachmentList({ files }: { files: Attachment[] }) {
if (!files.length) return <p className="review-meta">暂无附件</p>;
return <ul className="attachment-list">{files.map(file => <li key={file.id}>
<FileText size={18} aria-hidden="true"/>
<div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div>
<a className="icon-button" href={appPath(`/api/attachments/${file.id}`)} download={file.name} aria-label={`下载 ${file.name}`}><Download size={17}/></a>
</li>)}</ul>;
}
export function AttachmentPicker({ files, onChange, disabled, uploading, onUploadingChange, onNewUpload, inputRef, compact = false }: {
inputRef?: RefObject<HTMLInputElement | null>; compact?: boolean;
files: Attachment[]; onChange: (files: Attachment[]) => void; disabled: boolean; uploading: boolean;
onUploadingChange: (busy: boolean) => void; onNewUpload: (file: Attachment) => void;
}) {
const localInput = useRef<HTMLInputElement>(null);
const input = inputRef ?? localInput;
const inFlight = useRef(false);
const [errors, setErrors] = useState<string[]>([]);
const [progress, setProgress] = useState('');
const [recoverable, setRecoverable] = useState<Attachment[]>([]);
const [recoveryLoading, setRecoveryLoading] = useState(true);
const [recoveryError, setRecoveryError] = useState('');
const [recoveryOpen, setRecoveryOpen] = useState(false);
const recoveryRequest = useRef<AbortController | null>(null);
const loadRecovery = useCallback(() => {
recoveryRequest.current?.abort();
const controller = new AbortController();
recoveryRequest.current = controller;
const timeout = setTimeout(() => controller.abort(), 15000);
return fetch(appPath('/api/attachments'), { signal: controller.signal, cache: 'no-store' })
.then(async response => {
const result = await response.json().catch(() => null) as { attachments?: Attachment[]; error?: string } | null;
if (!response.ok || !Array.isArray(result?.attachments)) throw new Error(result?.error || '未能加载未保存附件,请重试。');
return result.attachments;
})
.then(attachments => { if (recoveryRequest.current === controller) setRecoverable(attachments); })
.catch(error => {
// Superseded requests and unmounted pickers must not replace the latest result.
if (recoveryRequest.current === controller) setRecoveryError(controller.signal.aborted ? '未保存附件加载超时,请重试。' : error instanceof Error ? error.message : '未能加载未保存附件,请重试。');
})
.finally(() => {
clearTimeout(timeout);
if (recoveryRequest.current === controller) { recoveryRequest.current = null; setRecoveryLoading(false); }
});
}, []);
function refreshRecovery() { setRecoveryLoading(true); setRecoveryError(''); void loadRecovery(); }
useEffect(() => {
void loadRecovery();
return () => { recoveryRequest.current?.abort(); recoveryRequest.current = null; };
}, [loadRecovery]);
const available = recoverable.filter(file => !files.some(selected => selected.id === file.id));
async function discard(file: Attachment) {
onUploadingChange(true);
try {
const response = await fetch(appPath('/api/attachments/' + file.id), { method: 'DELETE' });
if (!response.ok) throw new Error('该附件可能已保存,请刷新后核对。');
setRecoverable(previous => previous.filter(item => item.id !== file.id));
} catch (error) { setErrors([error instanceof Error ? error.message : '附件移除失败,请重试。']); }
finally { onUploadingChange(false); }
}
async function upload(selected: File[]) {
if (!selected.length || inFlight.current || disabled) return;
const issues: string[] = [];
const allowed: File[] = [];
for (const file of selected) {
if (!file.size) issues.push(`${file.name}:空文件无法上传。`);
else if (file.size > MAX_ATTACHMENT_BYTES) issues.push(`${file.name}:超过 20 MB,请压缩后重新选择。`);
else if (files.length + allowed.length >= MAX_ATTACHMENTS) issues.push(`${file.name}:每条需求最多 10 个附件。`);
else allowed.push(file);
}
setErrors(issues);
if (!allowed.length) return;
inFlight.current = true;
onUploadingChange(true);
const uploaded = [...files];
try {
for (let index = 0; index < allowed.length; index++) {
const file = allowed[index];
setProgress(`正在上传 ${index + 1}/${allowed.length}:${file.name}`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 120000);
let quotaReached = false;
try {
const body = new FormData(); body.append('file', file);
const response = await fetch(appPath('/api/attachments'), { method: 'POST', body, signal: controller.signal });
const result = await response.json().catch(() => ({})) as { error?: string; attachment?: Attachment };
if (response.status === 409) { quotaReached = true; setRecoveryOpen(true); refreshRecovery(); }
if (!response.ok || !result.attachment) throw new Error(result.error || '上传失败,请重新选择此文件重试。');
uploaded.push(result.attachment);
onNewUpload(result.attachment);
onChange([...uploaded]);
} catch (error) {
issues.push(`${file.name}:${controller.signal.aborted ? '上传超时,请重新选择此文件重试。' : error instanceof Error ? error.message : '上传失败,请重新选择重试。'}`);
if (quotaReached && index < allowed.length - 1) issues.push('本批剩余文件尚未上传,请先选用或清理未保存附件,再重新选择文件。');
setErrors([...issues]);
} finally { clearTimeout(timeout); }
if (quotaReached) break;
}
} finally { inFlight.current = false; onUploadingChange(false); setProgress(''); }
}
return <div className="attachment-picker span-two">
{!compact && <div className="attachment-heading"><span>文件附件</span><small>{files.length}/{MAX_ATTACHMENTS}</small></div>}
<p className="attachment-help" id="attachment-help">可上传文档、图片等参考材料,每个文件不超过 20 MB,最多 10 个。保存需求后生效。</p>
<input ref={input} className="attachment-input" type="file" multiple aria-label="选择文件附件" aria-describedby="attachment-help" disabled={disabled || uploading} onChange={event => { const selected = Array.from(event.currentTarget.files ?? []); event.currentTarget.value = ''; void upload(selected); }}/>
{!compact && <button className="btn" type="button" disabled={disabled || uploading || files.length >= MAX_ATTACHMENTS} onClick={() => input.current?.click()}><Paperclip size={16}/>{uploading ? '正在上传…' : '上传附件'}</button>}
{progress && <p className="attachment-progress" role="status"><LoaderCircle size={16} className="attachment-spinner"/>{progress}</p>}
{errors.length > 0 && <div className="error-banner attachment-errors" role="alert"><ul>{errors.map((message, index) => <li key={index}>{message}</li>)}</ul></div>}
{files.length > 0 && <ul className="attachment-list">{files.map(file => <li key={file.id}>
<FileText size={18} aria-hidden="true"/>
<div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div>
<button className="icon-button" type="button" disabled={disabled || uploading} aria-label={`移除 ${file.name}`} onClick={() => { onChange(files.filter(item => item.id !== file.id)); setRecoverable(previous => previous.filter(item => item.id !== file.id)); setErrors([]); }}><X size={17}/></button>
</li>)}</ul>}
<div className="attachment-recovery-controls">
{recoveryLoading ? <p className="attachment-help" role="status">正在读取未保存附件…</p> : recoveryError ? <div className="error-banner attachment-errors" role="alert"><span>未保存附件列表加载失败:{recoveryError}</span><button className="btn" type="button" disabled={disabled || uploading} onClick={refreshRecovery}><RotateCw size={15}/>重新加载未保存附件</button></div> : <button className="text-button" type="button" disabled={disabled || uploading} onClick={refreshRecovery}><RotateCw size={14}/>刷新未保存附件</button>}
</div>
{available.length > 0 && <details className="attachment-recovery" open={recoveryOpen} onToggle={event => setRecoveryOpen(event.currentTarget.open)}><summary>找回未保存的附件({available.length})</summary><p className="attachment-help">此前已上传但尚未保存到需求的文件,24 小时内可选用。选用后移除或取消编辑会保留原文件;“清理”会删除文件,请核对其他窗口是否仍在使用。</p><ul className="attachment-list">{available.map(file => <li key={file.id}><div className="attachment-description"><a href={appPath(`/api/attachments/${file.id}`)} download={file.name}>{file.name}</a><small>{formatFileSize(file.size)}</small></div><button className="btn" type="button" disabled={disabled || uploading || files.length >= MAX_ATTACHMENTS} aria-label={`选用 ${file.name}`} onClick={() => onChange([...files, file])}>选用</button><button className="icon-button" type="button" disabled={disabled || uploading} aria-label={`清理未保存附件 ${file.name}`} onClick={() => void discard(file)}><X size={17}/></button></li>)}</ul></details>}
<p className="attachment-help">{compact ? '文档链接可在下方填写。' : '链接可继续填写在上方。'}修改已有附件后需保存;历史评审引用的文件仍会保留。</p>
</div>;
}
+17 -9
View File
@@ -1,25 +1,33 @@
'use client';
import { useState } from 'react';
import { ArrowRight, Bell, ChevronRight, Search, SlidersHorizontal, FileText, Lightbulb } from 'lucide-react';
import { ArrowRight, Bell, ChevronRight, Search, SlidersHorizontal, FileText, Lightbulb, RotateCw } from 'lucide-react';
import { type Demand, needsAction } from '@/lib/demand';
import { reviewStage } from '@/lib/demand-review';
import { workflowTask, dueDate } from '@/lib/workflow';
export function Status({d}:{d:Demand}){const style=d.status==='待验收'?'purple':d.status==='开发中'?'blue':d.status==='已完成'?'green':d.status==='待发布'||d.status==='已上线'?'teal':d.status==='已取消'?'gray':d.status==='草稿'?'gray':'neutral';return <span className={'status '+style}>{d.status}</span>}
export function Dashboard({demands,view,onView,onOpen,onNew,onGuide,demo,onMode}:{demands:Demand[];view:string;onView:(v:string)=>void;onOpen:(d:Demand)=>void;onNew:()=>void;onGuide:()=>void;demo:boolean;onMode:()=>void}){
export function Dashboard({demands,view,onView,onOpen,onNew,onGuide,onRefresh,loading,unavailable}:{demands:Demand[];view:string;onView:(v:string)=>void;onOpen:(d:Demand)=>void;onNew:()=>void;onGuide:()=>void;onRefresh:()=>void;loading:boolean;unavailable:boolean}){
const [tab,setTab]=useState('全部需求');const [query,setQuery]=useState('');const [filterOpen,setFilterOpen]=useState(false);const [priority,setPriority]=useState('全部优先级');const [project,setProject]=useState('全部项目');
function openView(nextView:string,nextTab='全部需求'){
setTab(nextTab);setQuery('');setPriority('全部优先级');setProject('全部项目');setFilterOpen(false);onView(nextView);
}
const pending=(loading||unavailable)&&demands.length===0;
const submitted=demands.filter(d=>d.status!=='草稿');const inProgress=submitted.filter(d=>['已排期','开发中'].includes(d.status));const todos=demands.filter(needsAction);const completed=demands.filter(d=>d.status==='已完成');
const base=view==='草稿箱'?demands.filter(d=>d.status==='草稿'):view==='待我处理'?todos:submitted;
const filtered=base.filter(d=>(tab==='全部需求'||view==='草稿箱'||(tab==='进行中'?['已排期','开发中'].includes(d.status):d.status===tab))&&(priority==='全部优先级'||d.fields.priority===priority)&&(project==='全部项目'||d.fields.project===project)&&(d.fields.title+d.id+d.fields.department+d.fields.owner).toLowerCase().includes(query.toLowerCase()));
const today=new Date().toLocaleDateString('sv-SE',{timeZone:'Asia/Shanghai'});
const recent=view==='我的工作台'&&!query&&tab==='全部需求'&&priority==='全部优先级'&&project==='全部项目';const rows=recent?filtered.slice(0,5):filtered;
return <>
<div className="page-heading"><div><h1>{view}</h1><p>{view==='我的工作台'?'一起让每一个好需求,有序落地。':view==='草稿箱'?'还没写完的想法,在这里继续。':view==='待我处理'?'补齐业务信息、确认结果,让需求继续向前。':'从业务诉求到交付完成,进展都在这里。'}</p></div><button className="btn primary" onClick={onNew}><span className="plus">+</span>登记新需求</button></div>
{view==='我的工作台'&&<><div className="stats">{[['我的需求',submitted.length,'我的需求'],['进行中',inProgress.length,'进行中'],['待我处理',todos.length,'待我处理'],['已完成',completed.length,'已完成']].map(([label,value,to])=><button key={label} onClick={()=>{if(to==='进行中'||to==='已完成'){setTab(String(to));onView('我的需求')}else onView(String(to))}}><span>{label}</span><strong>{value}</strong></button>)}</div><div className="reminder"><Bell size={20}/><strong>待办提醒</strong><span className="reminder-divider"/><span>{todos.length?`你有 ${todos.filter(d=>d.status==='待评审').length} 项需求待补充,${todos.filter(d=>d.status==='待验收').length} 项待验收`:'当前没有待办,需求进展尽在掌握。'}</span><button className="text-button" onClick={()=>{setTab('全部需求');onView('待我处理')}}>查看待办<ArrowRight size={17}/></button></div></>}
<div className={'workspace-grid '+(view!=='我的工作台'?'full-width':'')}><section className="panel demand-panel"><div className="panel-heading"><h2>{view==='我的工作台'?'最近需求':view==='待我处理'?'需要你处理':view==='草稿箱'?'未提交的草稿':'需求列表'}</h2>{view==='我的工作台'?<button className="text-button" onClick={()=>onView('我的需求')}>查看全部<ArrowRight size={16}/></button>:<span className="muted">{filtered.length} 条需求</span>}</div>
{view!=='草稿箱'&&<div className="tabs" role="tablist" aria-label="需求状态">{['全部需求','进行中','待验收','已完成'].map(t=><button key={t} role="tab" aria-selected={tab===t} className={tab===t?'selected':''} onClick={()=>setTab(t)}>{t}</button>)}</div>}
<div className="page-heading"><div><h1>{view}</h1><p>{view==='我的工作台'?'一起让每一个好需求,有序落地。':view==='全部需求'?'查看所有已登记需求、评审进展与附件;个人草稿仅本人可见。':view==='草稿箱'?'还没写完的想法,在这里继续。':view==='待我处理'?'补齐业务信息、确认结果,让需求继续向前。':'从业务诉求到交付完成,进展都在这里。'}</p></div><div className="page-actions"><button className="btn" onClick={onRefresh} disabled={loading}><RotateCw size={16}/>刷新需求</button><button className="btn primary" onClick={onNew}><span className="plus">+</span>登记新需求</button></div></div>
{view==='我的工作台'&&<><div className="stats">{[['我的需求',submitted.length,'我的需求'],['进行中',inProgress.length,'进行中'],['待我处理',todos.length,'待我处理'],['已完成',completed.length,'已完成']].map(([label,value,to])=><button key={label} onClick={()=>{if(to==='进行中'||to==='已完成')openView('我的需求',String(to));else openView(String(to))}}><span>{label}</span><strong>{pending?'—':value}</strong></button>)}</div><div className="reminder"><Bell size={20}/><strong>待办提醒</strong><span className="reminder-divider"/><span>{pending?(loading?'正在加载待办…':'待办信息暂不可用'):todos.length?`你有 ${todos.length} 项待办${todos.some(d=>dueDate(d)&&dueDate(d)!<today)?',其中有已逾期事项':''}`:'当前没有待办,需求进展尽在掌握。'}</span><button className="text-button" onClick={()=>openView('待我处理')}>查看待办<ArrowRight size={17}/></button></div></>}
<div className={'workspace-grid '+(view!=='我的工作台'?'full-width':'')}><section className="panel demand-panel"><div className="panel-heading"><h2>{view==='我的工作台'?'最近需求':view==='待我处理'?'需要你处理':view==='草稿箱'?'未提交的草稿':'需求列表'}</h2>{view==='我的工作台'?<button className="text-button" onClick={()=>openView('我的需求')}>查看全部<ArrowRight size={16}/></button>:<span className="muted">{pending?'—':filtered.length} 条需求</span>}</div>
{view!=='草稿箱'&&<div className="tabs" role="tablist" aria-label="需求状态">{['全部需求','待评审','已排期','进行中','待验收','待发布','已上线','已完成','已取消'].map(t=><button key={t} role="tab" aria-selected={tab===t} className={tab===t?'selected':''} onClick={()=>setTab(t)}>{t}</button>)}</div>}
<div className="table-toolbar"><label className="search-field"><Search size={18}/><input aria-label="搜索需求" value={query} onChange={e=>setQuery(e.target.value)} placeholder="搜索需求名称或编号"/></label><button className={'btn filter-button '+(filterOpen?'pressed':'')} onClick={()=>setFilterOpen(!filterOpen)} aria-expanded={filterOpen}><SlidersHorizontal size={17}/>筛选</button></div>
{filterOpen&&<div className="filters"><label>优先级<select value={priority} onChange={e=>setPriority(e.target.value)}>{['全部优先级','P0','P1','P2'].map(p=><option key={p}>{p}</option>)}</select></label><label>项目<select value={project} onChange={e=>setProject(e.target.value)}>{['全部项目',...new Set(demands.map(d=>d.fields.project).filter(Boolean))].map(p=><option key={p}>{p}</option>)}</select></label><button className="text-button" onClick={()=>{setPriority('全部优先级');setProject('全部项目');setQuery('');setTab('全部需求')}}>重置</button></div>}
<div className="table-wrap"><table><thead><tr><th>需求名称</th><th>状态</th><th>优先级</th><th>期望上线</th></tr></thead><tbody>{rows.map(d=><tr key={d.id}><td><button className="demand-title" onClick={()=>onOpen(d)}>{d.fields.title}<ChevronRight size={15}/></button><div className="row-meta">{d.id}<span>·</span>{d.fields.department||'未填写部门'}</div></td><td><Status d={d}/>{d.status==='待评审'&&!d.reviewReady&&<span className="supplement">资料待补充</span>}{d.blocked&&<span className="supplement">阻塞</span>}</td><td><span className={'priority p'+d.fields.priority.slice(1)}><i/>{d.fields.priority} {d.fields.priority==='P0'?'紧急':d.fields.priority==='P1'?'高':'普通'}</span></td><td className="date-cell">{d.fields.noFixedDate?'无固定日期':d.fields.expectedDate?d.fields.expectedDate.slice(5):'待填写'}</td></tr>)}</tbody></table></div>
{!rows.length&&<div className="empty-state">{query?<Search size={32}/>:<FileText size={32}/>}<h3>{query||priority!=='全部优先级'?'没有匹配的需求':view==='待我处理'?'所有待办都处理好了':view==='草稿箱'?'还没有草稿':'从第一个需求开始'}</h3><p>{query?'试试其他关键词或调整筛选条件。':'把业务问题写下来,让每一步都有据可循。'}</p><button className="btn" onClick={onNew}>登记新需求<ArrowRight size={16}/></button></div>}
<div className="table-wrap"><table><thead><tr><th>需求名称</th><th>状态</th><th>优先级</th><th>期望上线</th></tr></thead><tbody>{rows.map(d=><tr key={d.id}><td><button className="demand-title" onClick={()=>onOpen(d)}>{d.fields.title}<ChevronRight size={15}/></button><div className="row-meta">{d.id}<span>·</span>{d.fields.department||'未填写部门'}{view==='全部需求'&&<><span>·</span>负责人:{d.fields.owner||'待补充'}</>}{d.access?.developer&&<><span>·</span>我负责开发</>}</div></td><td><Status d={d}/>{(workflowTask(d)||d.status==='待评审')&&<span className="supplement">{workflowTask(d)||reviewStage(d)}</span>}{dueDate(d)&&dueDate(d)!<today&&<span className="workflow-due">已逾期 · {dueDate(d)}</span>}{d.blocked&&<span className="supplement">阻塞</span>}</td><td><span className={'priority p'+d.fields.priority.slice(1)}><i/>{d.fields.priority} {d.fields.priority==='P0'?'紧急':d.fields.priority==='P1'?'高':'普通'}</span></td><td className="date-cell">{d.fields.noFixedDate?'无固定日期':d.fields.expectedDate?d.fields.expectedDate.slice(5):'待填写'}</td></tr>)}</tbody></table></div>
{!rows.length&&pending&&<div className="empty-state" role="status"><h3>{loading?'正在加载需求…':'暂时无法加载需求'}</h3>{!loading&&<p>请使用上方的“重新加载”按钮重试。</p>}</div>}
{!rows.length&&!pending&&<div className="empty-state">{query?<Search size={32}/>:<FileText size={32}/>}<h3>{query||priority!=='全部优先级'?'没有匹配的需求':view==='待我处理'?'所有待办都处理好了':view==='草稿箱'?'还没有草稿':view==='全部需求'?'暂时没有正式需求':'从第一个需求开始'}</h3><p>{query?'试试其他关键词或调整筛选条件。':'把业务问题写下来,让每一步都有据可循。'}</p><button className="btn" onClick={onNew}>登记新需求<ArrowRight size={16}/></button></div>}
{view!=='我的工作台'&&rows.length>0&&<div className="table-footer">共 {rows.length} 条,已显示全部结果</div>}</section>
{view==='我的工作台'&&<aside className="right-rail"><section className="panel tips-panel"><h2><Lightbulb size={20}/>需求提交小贴士</h2>{[['说清业务问题','描述背景、现状与痛点'],['明确预期结果','说明希望达到的目标和价值'],['准备验收标准','给出可衡量、可验收的标准']].map(([title,desc],i)=><div className="tip" key={title}><span>{i+1}</span><div><h3>{title}</h3><p>{desc}</p></div></div>)}<button className="text-button tips-link" onClick={onGuide}>查看填写指引<ArrowRight size={16}/></button></section><section className="panel process-panel"><h2>流程一览</h2><ol>{['需求登记','评审排期','设计开发','业务验收','上线完成'].map((s,i)=><li key={s}><span className={i===0?'current':''}>{i+1}</span>{s}</li>)}</ol></section></aside>}</div>
<div className="workspace-footer"><span>{demo?'当前展示示例数据,登记后将进入你的工作空间。':'期望上线为业务期望,正式交付时间以评审计划为准。'}</span><button onClick={onMode}>{demo?'查看我的数据':'体验示例'}<ArrowRight size={14}/></button></div>
<div className="workspace-footer"><span>期望上线为业务期望,正式交付时间以评审计划为准。</span></div>
</>;
}
+36 -20
View File
@@ -1,38 +1,54 @@
'use client';
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { X, PencilLine, GitBranch, Download, ArrowRight, CircleAlert, CheckCircle2, Clock3, Info } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { type Demand, statuses } from '@/lib/demand';
import { AlertDialog, AlertDialogContent, AlertDialogTitle, AlertDialogDescription, AlertDialogCancel, AlertDialogAction } from '@/components/ui/alert-dialog';
import { AttachmentList } from './attachments';
import { DemandReviewPanel } from './review';
import { reviewStage } from '@/lib/demand-review';
import { Status } from './dashboard';
import { WorkflowPanel } from './workflow';
import { planConfirmed, latestRelease } from '@/lib/workflow';
import { type SaveInput } from './form';
const date=(s:string)=>new Date(s).toLocaleString('zh-CN',{year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false,timeZone:'Asia/Shanghai'});
function FieldView({label,value}:{label:string;value:string}){return <div className="detail-field"><span>{label}</span><p>{value||'待补充'}</p></div>}
export function DemandDetail({d,onClose,onEdit,onAction,busy,error}:{d:Demand;onClose:()=>void;onEdit:(d:Demand)=>void;onAction:(body:SaveInput)=>Promise<void>;busy:boolean;error:string}){
const [tab,setTab]=useState('需求详情');const [mode,setMode]=useState('');const [content,setContent]=useState('');const [reason,setReason]=useState('');const [results,setResults]=useState<string[]>(d.acceptance?.items.map(()=> '待测')??[]);const [notes,setNotes]=useState('');const [confirm,setConfirm]=useState(false);const [localError,setLocalError]=useState('');
const f=d.fields;const current=statuses.indexOf(d.status as typeof statuses[number]);
export function DemandDetail({d,onClose,onEdit,onAction,busy,error,initialTab,onTabChange}:{initialTab?:string;onTabChange?:(tab:string)=>void;d:Demand;onClose:()=>void;onEdit:(d:Demand)=>void;onAction:(body:SaveInput)=>Promise<void>;busy:boolean;error:string}){
const [tab,setTab]=useState(initialTab??(d.status==='待评审'&&d.reviewReady?'需求评审':['已排期','开发中','待验收','待发布','已上线','已完成'].includes(d.status)?'交付流程':'需求详情'));const [reviewDirty,setReviewDirty]=useState(false);const [reviewExit,setReviewExit]=useState<{tab?:string}|null>(null);const [mode,setMode]=useState('');const [content,setContent]=useState('');const [reason,setReason]=useState('');const [results,setResults]=useState<string[]>(d.acceptance?.items.map(()=> '待测')??[]);const [notes,setNotes]=useState('');const [confirm,setConfirm]=useState(false);const [localError,setLocalError]=useState('');
const errorRef=useRef<HTMLDivElement>(null);
useEffect(()=>{if(error||localError)errorRef.current?.scrollIntoView({block:'nearest'});},[error,localError]);
const business=d.access?.business??true;
function leaveReview(nextTab?:string){setReviewDirty(false);if(nextTab){setTab(nextTab);onTabChange?.(nextTab);setMode('');setLocalError('')}else onClose();}
function requestLeave(nextTab?:string){if(busy)return;if(reviewDirty)setReviewExit({tab:nextTab});else leaveReview(nextTab);}
const f=d.fields;const current=statuses.indexOf(d.status as typeof statuses[number]);const emergency=['已上线','已完成'].includes(d.status)?latestRelease(d)?.emergency:undefined;
async function submit(){setLocalError('');if(mode==='change'&&(!content.trim()||!reason.trim())){setLocalError('请填写变更内容与原因。');return;}if(mode==='cancel'&&!reason.trim()){setLocalError('请填写取消需求的原因。');return;}if(mode==='accept'&&(results.some(r=>r==='待测')||!notes.trim()||!confirm)){setLocalError('请逐项完成验收、填写遗留问题及处理计划,并明确确认结论。');return;}
try{await onAction({action:mode,id:d.id,revision:d.revision,content,reason,results,notes,confirm,testVersion:d.acceptance?.testVersion,version:f.version});setMode('');setContent('');setReason('');}catch{}}
try{await onAction({action:mode,id:d.id,revision:d.revision,content,reason,results,notes,confirm,testVersion:d.acceptance?.testVersion,version:f.version,round:d.acceptance?.round});setMode('');setContent('');setReason('');}catch{}}
function exportRecord(){const lines=[`# ${d.id} · ${f.title}`,`状态:${d.status} | 文档版本:${f.version}`,`需求负责人:${f.owner} | 登记人:${f.proposer}`,`\n## 需求内容`,...Object.entries(f).map(([k,v])=>`${k}: ${v}`),'\n## 过程记录',...d.history.map(h=>`${date(h.time)} ${h.actor} ${h.action}\n${h.detail}`),'\n## 完整记录(含验收与变更)','```json',JSON.stringify(d,null,2),'```'];const url=URL.createObjectURL(new Blob([lines.join('\n')],{type:'text/markdown;charset=utf-8'}));const a=document.createElement('a');a.href=url;a.download=d.id+'.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
return <Dialog open onOpenChange={open=>{if(!open&&!mode&&!busy)onClose()}}><DialogContent className="demand-modal detail-modal" showCloseButton={false} onInteractOutside={e=>{if(mode)e.preventDefault()}}><div className="detail-heading"><div className="detail-eyeline"><span>{d.id}</span><Status d={d}/>{d.demo&&<span className="demo-tag">示例</span>}<button className="icon-button" aria-label="关闭需求详情" onClick={()=>{if(mode){setMode('');setLocalError('')}else onClose()}} disabled={busy}><X size={20}/></button></div><DialogTitle className="detail-title">{f.title}</DialogTitle><DialogDescription className="detail-description">{f.project} / {f.module} <span>·</span>{f.department} <span>·</span>负责人:{f.owner}</DialogDescription></div>
<div className="detail-progress">{statuses.map((s,i)=><div key={s} className={i===current?'current':i<current?'done':''}><span>{i<current?<CheckCircle2 size={15}/>:i+1}</span><b>{s}</b></div>)}</div>
<div className="tabs detail-tabs" role="tablist" aria-label="需求详情栏目">{['需求详情','进度记录','需求变更','业务验收'].map(t=><button role="tab" aria-selected={tab===t} className={tab===t?'selected':''} key={t} onClick={()=>{setTab(t);setMode('');setLocalError('')}}>{t}{t==='需求变更'&&d.changes.length>0&&<small>{d.changes.length}</small>}</button>)}</div>
return <><Dialog open onOpenChange={open=>{if(!open&&!busy)requestLeave()}}><DialogContent className="demand-modal detail-modal" showCloseButton={false} onInteractOutside={e=>{if(mode||reviewDirty)e.preventDefault()}}><div className="detail-heading"><div className="detail-eyeline"><span>{d.id}</span><Status d={d}/><button className="icon-button" aria-label="关闭需求详情" onClick={()=>requestLeave()} disabled={busy}><X size={20}/></button></div><DialogTitle className="detail-title">{f.title}</DialogTitle><DialogDescription className="detail-description">{f.project} / {f.module} <span>·</span>{f.department} <span>·</span>负责人:{f.owner}</DialogDescription></div>
<div className="detail-progress">{statuses.map((s,i)=>{const done=i<current&&(s!=='待验收'||!emergency||emergency.followUp?.approved);return <div key={s} className={i===current?'current':done?'done':''}><span>{done?<CheckCircle2 size={15}/>:i+1}</span><b>{emergency&&s==='待验收'?'业务补验':emergency&&s==='待发布'?'紧急发布':s}</b></div>})}</div>
<div className="tabs detail-tabs" role="tablist" aria-label="需求详情栏目">{['需求详情','需求评审','交付流程','业务验收','缺陷','需求变更','进度记录'].map(t=><button role="tab" aria-selected={tab===t} className={tab===t?'selected':''} key={t} disabled={busy} onClick={()=>{if(t!==tab)requestLeave(t)}}>{t}{t==='需求变更'&&d.changes.length>0&&<small>{d.changes.length}</small>}</button>)}</div>
<div className="modal-scroll"><div className="detail-content">
{(error||localError)&&<div role="alert" className="error-banner"><CircleAlert size={17}/>{error||localError}</div>}
{d.demo&&<div className="info-banner detail-info"><Info size={17}/>当前为示例需求,验收和变更操作只用于体验,不影响实际业务数据。</div>}
{mode==='change'||mode==='cancel'?<div className="action-form"><h2>{mode==='change'?'提出需求变更':'确认取消需求'}</h2><p>{mode==='change'?'记录希望调整的内容,开发负责人评估影响、双方确认后,再更新范围与计划。':'取消后会保留需求及过程记录。请填写明确的业务原因。'}</p>{mode==='change'&&<label className="form-field"><span>变更内容<em>*</em></span><textarea rows={4} value={content} onChange={e=>setContent(e.target.value)} maxLength={5000} placeholder="当前内容是什么?希望调整为什么?"/></label>}<label className="form-field"><span>{mode==='change'?'变更原因':'取消原因'}<em>*</em></span><textarea rows={3} value={reason} onChange={e=>setReason(e.target.value)} maxLength={3000} placeholder="请说明业务背景及必要性"/></label></div>:<>
{tab==='需求详情'&&<><div className="detail-overview"><FieldView label="建议优先级" value={f.priority+' · '+(f.priority==='P0'?'紧急':f.priority==='P1'?'高':'普通')}/><FieldView label="期望上线" value={f.noFixedDate?'无固定日期':f.expectedDate}/><FieldView label="文档版本" value={f.version}/><FieldView label="登记日期" value={d.createdAt.slice(0,10)}/></div>{d.plan&&<section className="plan-strip"><h3><Clock3 size={17}/>已确认交付计划</h3><div><FieldView label="开发负责人" value={d.plan.developer}/><FieldView label="计划提测" value={d.plan.testDate}/><FieldView label="计划上线" value={d.plan.releaseDate}/></div></section>}
{(error||localError)&&<div ref={errorRef} role="alert" className="error-banner"><CircleAlert size={17}/>{error||localError}</div>}
{d.access&&!d.access.business&&!d.access.developer&&<p className="info-banner admin-readonly-notice"><Info size={17}/>{d.access.canTakeOverDevelopment?'原开发账号已停用或不可用,可在“需求评审”中接手开发职责。接手前仅可查看需求及附件。':'管理员查看模式:可查看需求、评审记录和附件,修改及确认由对应责任人操作。'}</p>}
{mode==='change'||mode==='cancel'?<div className="action-form"><h2>{mode==='change'?'提出需求变更':'确认取消需求'}</h2><p>{mode==='change'?'记录希望调整的内容,开发负责人评估影响、双方确认后,再更新范围与计划。':'取消后会保留需求及过程记录。请填写明确的业务原因。'}</p>{mode==='change'&&<label className="form-field"><span>变更内容<em>*</em></span><textarea rows={4} value={content} onChange={e=>{setContent(e.target.value);setReviewDirty(true)}} maxLength={5000} placeholder="当前内容是什么?希望调整为什么?"/></label>}<label className="form-field"><span>{mode==='change'?'变更原因':'取消原因'}<em>*</em></span><textarea rows={3} value={reason} onChange={e=>{setReason(e.target.value);setReviewDirty(true)}} maxLength={3000} placeholder="请说明业务背景及必要性"/></label></div>:<>
{tab==='需求详情'&&<><div className="detail-overview"><FieldView label="建议优先级" value={f.priority+' · '+(f.priority==='P0'?'紧急':f.priority==='P1'?'高':'普通')}/><FieldView label="期望上线" value={f.noFixedDate?'无固定日期':f.expectedDate}/><FieldView label="文档版本" value={f.version}/><FieldView label="登记日期" value={d.createdAt.slice(0,10)}/></div>{d.plan&&planConfirmed(d)&&<section className="plan-strip"><h3><Clock3 size={17}/>已确认交付计划</h3><div><FieldView label="开发负责人" value={d.plan.developer}/><FieldView label="计划提测" value={d.plan.testDate}/><FieldView label="计划上线" value={d.plan.releaseDate}/></div></section>}
<section className="detail-section"><h2>业务背景与目标</h2><FieldView label="业务背景及现有处理方式" value={f.background}/><FieldView label="影响对象及业务依据" value={f.impact}/><FieldView label="预期目标" value={f.goal}/><FieldView label="期望日期依据" value={f.noFixedDate?'无固定日期':f.dateReason}/></section>
<section className="detail-section"><h2>范围与验收标准</h2><FieldView label="实施范围及功能说明" value={f.scope}/><FieldView label="范围外事项" value={f.outOfScope}/><FieldView label="验收标准" value={f.criteria}/><FieldView label="优先级依据" value={f.priorityReason}/></section>
<section className="detail-section"><h2>数据与参考材料</h2><FieldView label="数据来源" value={f.noData?'本需求不涉及数据来源':f.dataSource}/>{!f.noData&&<FieldView label="数据提供人" value={f.dataContact}/>}<FieldView label="依赖与风险" value={f.risk}/><FieldView label="待确认事项" value={f.pending}/><FieldView label="参考材料" value={f.references||'暂无参考材料'}/><FieldView label="提出人及来源" value={f.proposer+' · '+f.source}/></section></>}
<section className="detail-section"><h2>评审方案</h2><p className="muted review-solution-note">{reviewStage(d)} · <button className="text-button" onClick={()=>requestLeave('需求评审')}>查看评审与确认记录</button></p><FieldView label="实施范围与功能说明" value={f.scope||'待需求评审时提出并确认'}/><FieldView label="范围外事项" value={f.outOfScope||'待需求评审时提出并确认'}/></section>
<section className="detail-section"><h2>验收与优先级</h2><FieldView label="验收标准" value={f.criteria}/><FieldView label="优先级依据" value={f.priorityReason}/></section>
<section className="detail-section"><h2>数据与参考材料</h2><FieldView label="数据来源" value={f.noData?'本需求不涉及数据来源':f.dataSource}/>{!f.noData&&<FieldView label="数据提供人" value={f.dataContact}/>}<FieldView label="依赖与风险" value={f.risk}/><FieldView label="待确认事项" value={f.pending}/><FieldView label="参考材料与链接" value={f.references||'暂无参考链接'}/><div className="detail-field"><span>文件附件</span><AttachmentList files={d.attachments??[]}/></div><FieldView label="提出人及来源" value={f.proposer+' · '+f.source}/></section></>}
{tab==='交付流程'&&<WorkflowPanel kind="delivery" d={d} onAction={onAction} busy={busy} onDirtyChange={setReviewDirty}/>}
{tab==='缺陷'&&<WorkflowPanel kind="defects" d={d} onAction={onAction} busy={busy} onDirtyChange={setReviewDirty}/>}
{tab==='需求评审'&&<DemandReviewPanel d={d} onAction={onAction} busy={busy} onDirtyChange={setReviewDirty}/>}
{tab==='进度记录'&&<div className="timeline">{[...d.history].reverse().map((h,i)=><article key={i}><div className="timeline-dot"/><div className="timeline-meta"><h3>{h.action}</h3><time>{date(h.time)}</time></div><p>{h.detail}</p><span>{h.actor}</span></article>)}</div>}
{tab==='需求变更'&&<>{!d.changes.length?<div className="empty-state"><GitBranch size={31}/><h3>暂无需求变更</h3><p>已确认需求的范围调整,会在这里保留记录。</p>{['已排期','开发中','待验收','待发布','已上线'].includes(d.status)&&<button className="btn" onClick={()=>setMode('change')}>提出变更<ArrowRight size={16}/></button>}</div>:d.changes.map((c,i)=><article className="change-record" key={i}><div><h3>变更 {String(i+1).padStart(2,'0')}</h3><span className="status neutral">{c.status}</span></div><FieldView label="变更内容" value={c.content}/><FieldView label="变更原因" value={c.reason}/><p className="muted">基于 {c.originalVersion} · {c.actor} · {date(c.time)}</p></article>)}</>}
{tab==='业务验收'&&<>{d.acceptance?<><div className="acceptance-intro"><h2>验收清单</h2><p>文档版本 {f.version} <span>·</span>测试版本 {d.acceptance.testVersion}</p><FieldView label="测试环境" value={d.acceptance.environment}/><FieldView label="操作与测试数据说明" value={d.acceptance.instructions}/><div className="deadline"><Clock3 size={15}/>反馈截止时间:{d.acceptance.deadline};超时不会自动通过。</div></div>
{d.acceptance.items.map((item,i)=><div className="acceptance-item" key={item.id}><div className="acceptance-item-top"><span>{item.id}</span><strong>{item.feature}</strong>{d.status==='待验收'&&<select aria-label={item.id+' 验收结果'} value={results[i]} onChange={e=>setResults(prev=>prev.map((r,j)=>i===j?e.target.value:r))}><option>待测</option><option>通过</option><option>不通过</option></select>}</div><p><span>场景/操作</span>{item.scenario}</p><p><span>预期结果</span>{item.expected}</p></div>)}
{d.status==='待验收'&&<div className="acceptance-confirm"><label className="form-field"><span>遗留问题、证据/缺陷及处理计划<em>*</em></span><textarea rows={3} value={notes} onChange={e=>setNotes(e.target.value)} maxLength={5000} placeholder="无问题请填“无”。有问题请注明验收项、复现步骤、实际结果、证据及处理计划。"/></label><label className="check-field"><input type="checkbox" checked={confirm} onChange={e=>setConfirm(e.target.checked)}/><span>我已逐项核对以上版本并确认验收结果;全部通过后,同意按约定发布计划上线。</span></label><button className="btn primary" disabled={busy} onClick={()=>{if(results.some(r=>r==='待测')||!notes.trim()||!confirm){setLocalError('请逐项完成验收、填写遗留问题及处理计划,并明确确认结论。');return;}onAction({action:'accept',id:d.id,revision:d.revision,results,notes,confirm,testVersion:d.acceptance?.testVersion,version:f.version}).catch(()=>{})}}><CheckCircle2 size={17}/>{busy?'提交中…':'提交验收结论'}</button></div>}
{tab==='需求变更'&&<WorkflowPanel kind="changes" d={d} onAction={onAction} busy={busy} onDirtyChange={setReviewDirty}/>}
{tab==='业务验收'&&<>{d.acceptance?<><div className="acceptance-intro"><h2>验收清单</h2><p>文档版本 {d.acceptance.documentVersion??f.version} <span>·</span>测试版本 {d.acceptance.testVersion}{d.acceptance.withdrawnAt?' · 已撤回,请以新一轮提测为准':''}</p><FieldView label="测试环境" value={d.acceptance.environment}/><FieldView label="操作与测试数据说明" value={d.acceptance.instructions}/><div className="deadline"><Clock3 size={15}/>反馈截止时间:{d.acceptance.deadline};超时不会自动通过。</div></div>
{d.acceptance.items.map((item,i)=><div className="acceptance-item" key={item.id}><div className="acceptance-item-top"><span>{item.id}</span><strong>{item.feature}</strong>{business&&d.status==='待验收'&&<select aria-label={item.id+' 验收结果'} value={results[i]} onChange={e=>{setResults(prev=>prev.map((r,j)=>i===j?e.target.value:r));setReviewDirty(true)}}><option>待测</option><option>通过</option><option>不通过</option></select>}</div><p><span>场景/操作</span>{item.scenario}</p><p><span>预期结果</span>{item.expected}</p></div>)}
{business&&d.status==='待验收'&&<div className="acceptance-confirm"><label className="form-field"><span>遗留问题、证据/缺陷及处理计划<em>*</em></span><textarea rows={3} value={notes} onChange={e=>{setNotes(e.target.value);setReviewDirty(true)}} maxLength={5000} placeholder="无问题请填“无”。有问题请注明验收项、复现步骤、实际结果、证据及处理计划。"/></label><label className="check-field"><input type="checkbox" checked={confirm} onChange={e=>{setConfirm(e.target.checked);setReviewDirty(true)}}/><span>我已逐项核对以上版本并确认验收结果;全部通过后,同意按约定发布计划上线。</span></label><button className="btn primary" disabled={busy} onClick={()=>{if(results.some(r=>r==='待测')||!notes.trim()||!confirm){setLocalError('请逐项完成验收、填写遗留问题及处理计划,并明确确认结论。');return;}onAction({action:'accept',id:d.id,revision:d.revision,results,notes,confirm,testVersion:d.acceptance?.testVersion,version:f.version,round:d.acceptance?.round}).catch(()=>{})}}><CheckCircle2 size={17}/>{busy?'提交中…':'提交验收结论'}</button></div>}
</>:<div className="empty-state"><CheckCircle2 size={32}/><h3>还未进入业务验收</h3><p>完成技术验证并提供测试版本后,即可逐项验收。</p></div>}
{d.acceptanceRecords?.map((r,i)=><div className="acceptance-record" key={i}><h3>{r.passed?'业务验收通过':'业务验收未通过'}</h3><p>文档 {r.version} · 测试 {r.testVersion}</p><p>遗留问题及处理计划:{r.notes}</p><span>{r.actor} · {date(r.time)}</span></div>)}</>}
{d.acceptanceRecords?.map((r,i)=><div className="acceptance-record" key={i}><h3>{r.passed?'业务验收通过':'业务验收未通过'}</h3><p>文档 {r.version} · 测试 {r.testVersion}</p><p>遗留问题及处理计划:{r.notes}</p>{r.items&&<details><summary>逐项验收结果({r.items.length})</summary>{r.items.map(item=><div className="acceptance-item" key={item.id}><div className="acceptance-item-top"><span>{item.id}</span><strong>{item.feature}</strong><b>{item.result}</b></div><p><span>场景/操作</span>{item.scenario}</p><p><span>预期结果</span>{item.expected}</p></div>)}</details>}<span>{r.actor} · {date(r.time)}</span></div>)}</>}
</>}
</div></div>
<footer className="modal-footer"><div className="footer-left"><button className="text-button muted" onClick={exportRecord}><Download size={16}/>导出记录</button>{!['已上线','已完成','已取消'].includes(d.status)&&!mode&&<button className="text-button danger-text" onClick={()=>{setMode('cancel');setReason('')}}>取消需求</button>}</div><div className="footer-right">{mode==='change'||mode==='cancel'?<><button className="btn" onClick={()=>{setMode('');setLocalError('')}} disabled={busy}>返回详情</button><button className={'btn '+(mode==='change'?'primary':'danger-button')} onClick={submit} disabled={busy}>{busy?'保存中…':mode==='change'?'提交变更':'确认取消'}</button></>:<>{['草稿','待评审'].includes(d.status)&&<button className="btn primary" onClick={()=>onEdit(d)}><PencilLine size={16}/>{d.status==='草稿'?'继续填写':'补充信息'}</button>}{['已排期','开发中','待验收','待发布','已上线'].includes(d.status)&&<button className="btn" onClick={()=>{setMode('change');setReason('')}}><GitBranch size={16}/>提出变更</button>}{d.status==='待验收'&&tab!=='业务验收'&&<button className="btn primary" onClick={()=>setTab('业务验收')}>开始验收<ArrowRight size={16}/></button>}</>}</div></footer>
<footer className="modal-footer"><div className="footer-left"><button className="text-button muted" onClick={exportRecord}><Download size={16}/>导出记录</button>{business&&!['已上线','已完成','已取消'].includes(d.status)&&!mode&&<button className="text-button danger-text" disabled={busy||reviewDirty} onClick={()=>{setMode('cancel');setReason('')}}>取消需求</button>}</div><div className="footer-right">{mode==='change'||mode==='cancel'?<><button className="btn" onClick={()=>requestLeave(tab)} disabled={busy}>返回详情</button><button className={'btn '+(mode==='change'?'primary':'danger-button')} onClick={submit} disabled={busy}>{busy?'保存中…':mode==='change'?'提交变更':'确认取消'}</button></>:<>{business&&['草稿','待评审'].includes(d.status)&&<button className="btn" disabled={busy} onClick={()=>{if(reviewDirty){setLocalError('请先保存评审输入,或切换栏目放弃后再编辑业务信息。');return;}onEdit(d)}}><PencilLine size={16}/>{d.status==='草稿'?'继续填写':'补充信息'}</button>}{business&&['已排期','开发中','待验收','待发布','已上线'].includes(d.status)&&<button className="btn" onClick={()=>requestLeave('需求变更')}><GitBranch size={16}/>提出变更</button>}{d.status==='待评审'&&tab!=='需求评审'&&<button className="btn primary" onClick={()=>requestLeave('需求评审')}>需求评审<ArrowRight size={16}/></button>}{tab!=='交付流程'&&d.status!=='草稿'&&<button className="btn" onClick={()=>requestLeave('交付流程')}>交付流程<ArrowRight size={16}/></button>}{business&&d.status==='待验收'&&tab!=='业务验收'&&<button className="btn primary" onClick={()=>requestLeave('业务验收')}>开始验收<ArrowRight size={16}/></button>}</>}</div></footer>
</DialogContent></Dialog>
<AlertDialog open={reviewExit!==null} onOpenChange={open=>{if(!open)setReviewExit(null)}}><AlertDialogContent className="form-close-confirm"><AlertDialogTitle>放弃未保存的输入?</AlertDialogTitle><AlertDialogDescription>离开后,本次未提交的操作内容将丢失,已保存的记录会保留。</AlertDialogDescription><div className="form-close-actions"><AlertDialogCancel className="btn">继续填写</AlertDialogCancel><AlertDialogAction className="btn danger-button" onClick={()=>{leaveReview(reviewExit?.tab);setReviewExit(null)}}>放弃输入并离开</AlertDialogAction></div></AlertDialogContent></AlertDialog></>
}
+55 -19
View File
@@ -1,24 +1,47 @@
'use client';
import { useState } from 'react';
import { X, ArrowLeft, ArrowRight, Save, Send, Info, Check, CircleAlert, FilePenLine } from 'lucide-react';
import { useId, useRef, useState, type ReactNode } from 'react';
import { X, ArrowLeft, ArrowRight, Save, Send, Info, Check, CircleAlert, FilePenLine, Paperclip } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogContent, AlertDialogTitle, AlertDialogDescription, AlertDialogCancel, AlertDialogAction } from '@/components/ui/alert-dialog';
import { emptyFields, missingFields, type Fields, type Demand } from '@/lib/demand';
import type { Attachment } from '@/lib/attachments';
import { appPath } from '@/lib/base-path';
import { AttachmentPicker } from './attachments';
import { TemplateActions, type OpenTemplatePreview } from './template-actions';
import TemplatePreview from './template-preview';
import type { DocumentId } from '@/lib/documents';
import { MAX_ATTACHMENTS } from '@/lib/attachments';
export type SaveInput={action:string;id?:string;revision?:number;fields?:Fields;mode?:string;[key:string]:unknown};
export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}:{initial?:Demand;onSave:(body:SaveInput)=>Promise<void>;onClose:()=>void;busy:boolean;error:string;userName:string;existing:Demand[]}){
const [f,setF]=useState<Fields>(initial?.fields??{...emptyFields,proposer:userName,owner:userName});const [step,setStep]=useState(0);const [invalid,setInvalid]=useState<string[]>([]);const [exit,setExit]=useState(false);
export function DemandForm({initial,onSave,onClose,busy:saving,error,userName,existing}:{initial?:Demand;onSave:(body:SaveInput)=>Promise<void>;onClose:()=>void;busy:boolean;error:string;userName:string;existing:Demand[]}){
const inputPrefix=useId();const backgroundUpload=useRef<HTMLInputElement>(null);
// Guard the parent synchronously, before Radix registers the preview's layer.
const [templateId,setTemplateId]=useState<DocumentId|null>(null);const activePreview=useRef<DocumentId|null>(null);const templateTrigger=useRef<HTMLElement|null>(null);
const openPreview:OpenTemplatePreview=(id,trigger)=>{activePreview.current=id;templateTrigger.current=trigger;setTemplateId(id);};
function closePreview(){activePreview.current=null;setTemplateId(null);}
const [attachments,setAttachments]=useState<Attachment[]>(()=>initial?.attachments??[]);const [uploading,setUploading]=useState(false);const newUploads=useRef(new Set<string>());const busy=saving||uploading;
function releaseUploads(ids:Iterable<string>){for(const id of ids){void fetch(appPath('/api/attachments/'+id),{method:'DELETE',keepalive:true}).catch(()=>{});newUploads.current.delete(id);}}
function changeAttachments(next:Attachment[]){const kept=new Set(next.map(file=>file.id));releaseUploads(attachments.filter(file=>newUploads.current.has(file.id)&&!kept.has(file.id)).map(file=>file.id));setAttachments(next);}
function closeForm(){releaseUploads([...newUploads.current]);onClose();}
const [startingFields]=useState<Fields>(()=>({... (initial?.fields??{...emptyFields,proposer:userName,owner:userName})}));
const [f,setF]=useState<Fields>(startingFields);const [step,setStep]=useState(0);const [invalid,setInvalid]=useState<string[]>([]);const [exit,setExit]=useState(false);
const closeButton=useRef<HTMLButtonElement>(null);const returnFocus=useRef<HTMLElement|null>(null);
const changed=(Object.keys(startingFields) as (keyof Fields)[]).some(key=>f[key]!==startingFields[key])||attachments.map(file=>file.id).join(',')!==(initial?.attachments??[]).map(file=>file.id).join(',');
function requestClose(){if(activePreview.current){closePreview();return;}if(busy)return;if(changed){returnFocus.current=document.activeElement instanceof HTMLElement?document.activeElement:closeButton.current;setExit(true)}else closeForm();}
const set=(k:keyof Fields,v:string|boolean)=>setF(prev=>({...prev,[k]:v}));
const duplicate=existing.find(d=>d.id!==initial?.id&&f.title.trim().length>3&&d.fields.title.includes(f.title.trim()));
const field=(k:keyof Fields,label:string,placeholder:string,opts:{large?:boolean;full?:boolean;required?:boolean;type?:string;hint?:string;max?:number}={})=><label className={'form-field '+(opts.full?'span-two':'')} key={k}><span>{label}{opts.required&&<em>*</em>}</span>{opts.large?<textarea value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} rows={3} maxLength={opts.max??3000}/>:<input type={opts.type??'text'} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} maxLength={opts.max??100}/>} {opts.hint&&<small>{opts.hint}</small>}</label>;
async function save(mode:string){const m=mode==='draft'?(f.title.trim()?[]:['需求标题']):missingFields(f,mode==='review');setInvalid(m);if(m.length){setStep(mode==='review'?step:m.some(x=>['需求标题','所属项目','业务模块','提出人','所属部门','需求来源','需求负责人'].includes(x))?0:1);return;}await onSave({action:initial&&!initial.demo?'update':'create',id:initial?.demo?undefined:initial?.id,revision:initial?.revision,fields:f,mode});}
return <Dialog open onOpenChange={open=>{if(!open&&!busy)setExit(true)}}><DialogContent className="demand-modal form-modal" showCloseButton={false} onInteractOutside={e=>e.preventDefault()}><div className="modal-heading"><div className="modal-icon"><FilePenLine size={23}/></div><div><DialogTitle className="modal-title">{initial?'完善需求信息':'登记新需求'}</DialogTitle><DialogDescription className="modal-subtitle">一个独立业务目标,对应一条需求。先登记,再逐步完善。</DialogDescription></div><button className="icon-button" aria-label="关闭登记窗口" onClick={()=>setExit(true)} disabled={busy}><X size={20}/></button></div>
<div className="form-steps">{['基本信息','业务背景与目标','范围与验收','数据与参考材料'].map((s,i)=><button key={s} className={i===step?'current':i<step?'done':''} onClick={()=>setStep(i)}><span>{i<step?<Check size={14}/>:i+1}</span><b>{s}</b></button>)}</div>
const field=(k:keyof Fields,label:string,placeholder:string,opts:{large?:boolean;full?:boolean;required?:boolean;type?:string;hint?:string;max?:number;actions?:ReactNode}={})=>{
const id=inputPrefix+'-'+k;
return <div className={'form-field '+(opts.full?'span-two':'')} key={k}><div className="form-field-heading"><label htmlFor={id}>{label}{opts.required&&<em>*</em>}</label>{opts.actions}</div>{opts.large?<textarea id={id} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} rows={3} maxLength={opts.max??3000}/>:<input id={id} type={opts.type??'text'} value={String(f[k])} onChange={e=>set(k,e.target.value)} placeholder={placeholder} maxLength={opts.max??100}/>} {opts.hint&&<small>{opts.hint}</small>}</div>;
};
async function save(mode:string){const m=mode==='draft'?(f.title.trim()?[]:['需求标题']):missingFields(f,mode==='review');setInvalid(m);if(m.length){setStep(mode==='review'?step:m.some(x=>['需求标题','所属项目','业务模块','提出人','所属部门','需求来源','需求负责人'].includes(x))?0:1);return;}await onSave({action:initial?'update':'create',id:initial?.id,revision:initial?.revision,fields:f,mode,attachmentIds:attachments.map(file=>file.id)});}
return <><Dialog open onOpenChange={open=>{if(!open)requestClose()}}><DialogContent className="demand-modal form-modal" showCloseButton={false} aria-busy={busy} onInteractOutside={e=>e.preventDefault()} onEscapeKeyDown={e=>{if(e.defaultPrevented)return;if(activePreview.current){e.preventDefault();closePreview();}else if(busy)e.preventDefault();}}><div className="modal-heading"><div className="modal-icon"><FilePenLine size={23}/></div><div><DialogTitle className="modal-title">{initial?'完善需求信息':'登记新需求'}</DialogTitle><DialogDescription className="modal-subtitle">一个独立业务目标,对应一条需求。先登记,再逐步完善。</DialogDescription></div><button ref={closeButton} type="button" className="icon-button" aria-label="关闭登记窗口" onClick={requestClose} disabled={busy}><X size={20}/></button></div>
<div className="form-steps">{['基本信息','业务背景与目标','验收与优先级','数据与参考材料'].map((s,i)=><button key={s} className={i===step?'current':i<step?'done':''} onClick={()=>setStep(i)} disabled={busy}><span>{i<step?<Check size={14}/>:i+1}</span><b>{s}</b></button>)}</div>
<div className="modal-scroll"><div className="form-content">
{initial?.demo&&<div className="info-banner"><Info size={17}/>你正在参考示例填写,保存将创建一条属于你的新需求。</div>}
{exit&&<div className="exit-banner"><div><strong>本次编辑尚未保存</strong><p>你可以继续填写,或保存为草稿后离开。</p></div><button className="btn" onClick={()=>setExit(false)}>继续填写</button><button className="text-button danger-text" onClick={onClose}>放弃本次编辑</button></div>}
{(error||invalid.length>0)&&<div className="error-banner" role="alert"><CircleAlert size={18}/><span>{error||'请补充:'+invalid.join('、')}</span></div>}
<div className="form-section-heading"><h2>{['这是什么需求?','希望解决什么业务问题?','怎样才算做好了?','开发前,还需要哪些信息?'][step]}</h2><p>{['基本信息用于明确需求归属和联系人员。','用熟悉的业务语言描述,不需要填写技术实现方案。','这一部分可在登记后补充,提交评审前需填写完整。','材料可通过链接关联;简单需求可直接使用本表单作为需求正文。'][step]}</p></div>
<div className="form-grid">
<div className="form-section-heading"><h2>{['这是什么需求?','希望解决什么业务问题?','怎样才算做好了?','开发前,还需要哪些信息?'][step]}</h2><p>{['基本信息用于明确需求归属和联系人员。','用熟悉的业务语言描述,不需要填写技术实现方案。','这一部分可在登记后补充,提交评审前需填写完整。','参考材料可上传文件或填写链接;简单需求可直接使用本表单作为需求正文。'][step]}</p></div>
<fieldset className="form-grid" disabled={busy}>
{step===0&&<>
<div className="span-two contextual-template"><span>需要先整理基本信息?</span><TemplateActions documentId="registration" disabled={busy} onPreview={openPreview}/></div>
{field('title','需求标题','例如:订单管理—支持按订单状态导出',{full:true,required:true,hint:'建议使用“业务模块 + 动作或能力”,避免“页面优化”等笼统标题。'})}
{duplicate&&<div className="span-two info-banner"><Info size={16}/>已有相似需求「{duplicate.fields.title}」,请核对是否为同一目标。</div>}
{field('project','所属项目','例如:企业业务平台',{required:true})}{field('module','业务模块','例如:订单管理',{required:true})}
@@ -26,7 +49,9 @@ export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}
{field('department','所属部门','例如:销售部',{required:true})}{field('proposer','提出人','填写实际提出人',{required:true})}{field('owner','需求负责人','负责确认范围和业务验收的人',{required:true})}{field('source','需求来源','例如:销售周会、客户反馈、日常操作问题',{full:true,required:true,max:200})}
</>}
{step===1&&<>
{field('background','业务背景与现有处理方式','现在怎么做?具体遇到了什么问题?请补充实际案例或数据依据。',{large:true,full:true,required:true,max:6000})}
{field('background','业务背景与现有处理方式','简要说明当前做法和主要问题;详细内容可上传文件或填写文档链接。',{large:true,full:true,required:true,max:6000,hint:'这里可以简短说明。详细需求可按模板整理后上传,或在下方关联飞书文档。',actions:<><button className="text-button" type="button" disabled={busy||attachments.length>=MAX_ATTACHMENTS} onClick={()=>backgroundUpload.current?.click()}><Paperclip size={14}/>{uploading?'正在上传…':'上传文件'}</button><TemplateActions documentId="requirement" disabled={busy} onPreview={openPreview}/></>})}
<AttachmentPicker files={attachments} onChange={changeAttachments} disabled={saving} uploading={uploading} onUploadingChange={setUploading} onNewUpload={file=>newUploads.current.add(file.id)} inputRef={backgroundUpload} compact/>
{field('references','需求说明文档链接(选填)','粘贴填写后的飞书文档或其他参考链接,每行一条。',{large:true,full:true,max:5000,hint:'上传文件与填写链接可任选,也可以同时使用;这些材料会随需求保存。'})}
{field('impact','影响对象与业务依据','哪些用户或岗位受影响?影响范围有多大?依据是什么?',{large:true,full:true,required:true})}
{field('goal','预期目标','完成后希望达到什么结果?有量化依据时,请说明目标值与统计口径。',{large:true,full:true,required:true})}
<label className="check-field span-two"><input type="checkbox" checked={f.noFixedDate} onChange={e=>set('noFixedDate',e.target.checked)}/>没有固定的上线日期</label>
@@ -34,21 +59,32 @@ export function DemandForm({initial,onSave,onClose,busy,error,userName,existing}
<div className="info-banner span-two"><Info size={17}/>这是业务期望时间,正式交付计划由需求负责人和开发负责人评审确认。</div>
</>}
{step===2&&<>
{field('scope','实施范围与功能说明','F-01:本次需要支持的功能、操作步骤和业务规则。\nF-02:另一项相关功能。',{large:true,full:true,required:true,max:6000})}
{field('outOfScope','范围外事项','明确这次不做什么,无相关事项可填写“无”。',{large:true,full:true,required:true})}
{field('criteria','验收标准','AC-01 / F-01:在什么场景下执行什么操作,应得到什么结果。\n请覆盖正常流程、空数据、非法输入等关键异常。',{large:true,full:true,required:true,max:6000,hint:'每一项都应能实际验证,避免仅写“使用正常”“体验良好”。'})}
<div className="info-banner span-two"><Info size={17}/><span>实施范围与功能说明、范围外事项由开发责任人在需求评审时提出方案,并与业务方确认。</span></div>
{field('criteria','验收标准','AC-01:在什么业务场景下执行什么操作,应得到什么结果。\n请覆盖正常流程、空数据、非法输入等关键异常。',{large:true,full:true,required:true,max:6000,hint:'每项结果都应能实际验证;需求说明模板中的“验收标准”章节可供参考。',actions:<TemplateActions documentId="requirement" disabled={busy} onPreview={openPreview}/>})}
<label className="form-field"><span>建议优先级<em>*</em></span><select value={f.priority} onChange={e=>set('priority',e.target.value)}><option value="P2">P2 · 常规优化或储备</option><option value="P1">P1 · 近期业务目标</option><option value="P0">P0 · 业务阻塞或关键节点</option></select><small>最终优先级以评审结论为准。</small></label>
{field('priorityReason','优先级依据','说明业务影响、时间要求及依赖',{required:true,max:1000})}
</>}
{step===3&&<>
<label className="check-field span-two"><input type="checkbox" checked={f.noData} onChange={e=>set('noData',e.target.checked)}/>本需求不涉及数据来源</label>
{!f.noData&&<>{field('dataSource','数据来自哪里','平时从哪个系统、页面、报表或文件获取?需要哪些内容、多久更新?多个来源不一致时以谁为准?',{large:true,full:true,required:true})}{field('dataContact','由谁提供数据','提供人、部门及联系方式',{full:true,required:true,max:300})}</>}
{!f.noData&&<>{field('dataSource','数据来自哪里','平时从哪个系统、页面、报表或文件获取?需要哪些内容、多久更新?多个来源不一致时以谁为准?',{large:true,full:true,required:true,actions:<TemplateActions documentId="data-source" disabled={busy} onPreview={openPreview}/>})}{field('dataContact','由谁提供数据','提供人、部门及联系方式',{full:true,required:true,max:300})}</>}
{field('risk','依赖与风险','需要哪些系统或人员配合?有无风险及应对方式?无则填“无”。',{large:true,full:true,required:true})}
{field('pending','待确认事项','待确认问题 + 责任人 + 计划确认时间;无则填“无”。',{large:true,full:true,required:true})}
{field('version','需求文档版本','例如:v1.0',{required:true})}
{field('references','参考材料与链接','可填写 PRD、原型、截图或业务规则的受限共享链接,每行一条。',{large:true,full:true,max:5000,hint:'复杂需求请关联独立 PRD;账号密码等敏感信息通过约定受限渠道提供。'})}
<AttachmentPicker files={attachments} onChange={changeAttachments} disabled={saving} uploading={uploading} onUploadingChange={setUploading} onNewUpload={file=>newUploads.current.add(file.id)}/>
</>}
</div></div></div>
<footer className="modal-footer"><div className="footer-left">{(!initial||initial.status==='草稿'||initial.demo)&&<button className="btn" onClick={()=>save('draft')} disabled={busy}><Save size={16}/>保存草稿</button>}{step>0&&<button className="text-button back-button" onClick={()=>setStep(step-1)} disabled={busy}><ArrowLeft size={15}/>上一步</button>}</div><div className="footer-right">{step>=1&&<button className="btn" onClick={()=>save('register')} disabled={busy}>{busy?'保存中…':'先登记,稍后补充'}</button>}{step<3?<button className="btn primary" onClick={()=>setStep(step+1)} disabled={busy}>下一步<ArrowRight size={16}/></button>:<button className="btn primary" onClick={()=>save('review')} disabled={busy}><Send size={16}/>{busy?'提交中…':'提交评审'}</button>}</div></footer>
</fieldset></div></div>
<footer className="modal-footer"><div className="footer-left">{(!initial||initial.status==='草稿')&&<button className="btn" onClick={()=>save('draft')} disabled={busy}><Save size={16}/>保存草稿</button>}{step>0&&<button className="text-button back-button" onClick={()=>setStep(step-1)} disabled={busy}><ArrowLeft size={15}/>上一步</button>}</div><div className="footer-right">{step>=1&&<button className="btn" onClick={()=>save('register')} disabled={busy}>{uploading?'附件上传中…':saving?'保存中…':'先登记,稍后补充'}</button>}{step<3?<button className="btn primary" onClick={()=>setStep(step+1)} disabled={busy}>下一步<ArrowRight size={16}/></button>:<button className="btn primary" onClick={()=>save('review')} disabled={busy}><Send size={16}/>{uploading?'附件上传中…':saving?'提交中…':'提交评审'}</button>}</div></footer>
</DialogContent></Dialog>
{templateId&&<TemplatePreview documentId={templateId} onClose={closePreview} returnFocus={templateTrigger}/>}
<AlertDialog open={exit} onOpenChange={open=>{if(!busy)setExit(open)}}>
<AlertDialogContent className="form-close-confirm" onEscapeKeyDown={e=>{if(busy)e.preventDefault()}} onCloseAutoFocus={e=>{e.preventDefault();const target=returnFocus.current?.isConnected?returnFocus.current:closeButton.current;target?.focus({preventScroll:true})}}>
<AlertDialogTitle>放弃未保存的修改?</AlertDialogTitle>
<AlertDialogDescription>关闭后,本次未保存的修改和本窗口新上传的附件将被清理。找回或已保存的附件会保留。你可以返回继续填写并保存。</AlertDialogDescription>
<div className="form-close-actions">
<AlertDialogCancel className="btn" disabled={busy}>继续填写</AlertDialogCancel>
<AlertDialogAction className="btn danger-button" onClick={()=>{if(!busy)closeForm()}} disabled={busy}>放弃修改并关闭</AlertDialogAction>
</div>
</AlertDialogContent>
</AlertDialog></>
}
+21 -8
View File
@@ -1,10 +1,23 @@
'use client';
import { ArrowRight, BookOpen, Download, CheckCircle2, Info } from 'lucide-react';
const templates=['需求登记','需求文档','数据来源填写','验收记录','需求变更记录','缺陷记录','发布记录'];
export function Guide({onNew}:{onNew:()=>void}){return <><div className="page-heading"><div><h1>流程与规范</h1><p>把业务问题说清楚,让协作有共同依据。</p></div><button className="btn primary" onClick={onNew}>登记新需求<ArrowRight size={16}/></button></div><div className="guide-grid"><section className="panel guide-main"><h2>从想法到交付,你需要做什么?</h2>{[
import { ArrowRight, BookOpen, CheckCircle2, ExternalLink, Info } from 'lucide-react';
import { documents, FEISHU_TEMPLATE_DIRECTORY } from '@/lib/documents';
import { TemplateActions } from './template-actions';
export function Guide({ onNew }: { onNew: () => void }) {
return <>
<div className="page-heading"><div><h1>流程与规范</h1><p>把业务问题说清楚,让协作有共同依据。</p></div><button className="btn primary" onClick={onNew}>登记新需求<ArrowRight size={16}/></button></div>
<div className="guide-grid"><section className="panel guide-main"><h2>从想法到交付,你需要做什么?</h2>{[
['01', '先查询,再登记', '登记前搜索已有需求。同一业务目标合并维护;可以独立评审和验收的目标分别登记。', '填写标题、归属、提出人、需求负责人、业务背景、影响对象、目标及期望日期。'],
['02','补齐材料,提交评审','讲清楚“这次做什么、不做什么、怎样算完成”,让开发负责人可以评估。','补充范围、功能说明、验收标准、优先级依据、数据来源、依赖风险及文档版本。'],
['03','确认方案,跟进进度','设计定稿需明确对应设计版本,并由需求负责人确认“同意按此版本实施”。','业务期望上线日期不是交付承诺;正式排期由需求负责人和开发负责人评审确认。'],
['04','实际操作,逐项验收','使用测试环境和测试数据,按验收清单核对主要流程及异常结果。','记录文档版本、测试版本、每项结果、证据、遗留问题和处理计划,明确确认结论。'],
['05','确认上线,交付归档','业务验收通过后进入待发布;上线后仍需完成生产验证、观察和交接。','“已上线”不等于“已完成”。只有完成生产验证和约定观察,才结束需求。'],
].map(([n,title,desc,note])=><article className="guide-step" key={n}><span>{n}</span><div><h3>{title}</h3><p>{desc}</p><small>{note}</small></div></article>)}<div className="info-banner"><Info size={18}/>业务方说明业务来源和预期结果即可;数据库结构、接口和技术选型由开发负责人补充。</div></section><aside><section className="panel guide-docs"><h2><BookOpen size={20}/>配套规范与模板</h2><a href="/docs/开发SOP_公示版.md" download>软件开发流程管理规范<Download size={16}/></a>{templates.map((name,i)=><a href={'/docs/附件'+String(i+1).padStart(2,'0')+'_'+name+'模板.md'} download key={name}><span><small>{String(i+1).padStart(2,'0')}</small>{name}模板</span><Download size={15}/></a>)}</section><section className="panel guide-rules"><h2>几条重要约定</h2>{['草稿是填写辅助,不属于正式流程。','阻塞时保留当前状态,注明原因、责任人与跟进时间。','已确认范围需要调整时,提出变更并等待双方确认。','未达到原验收标准的问题,按缺陷处理。','验收不能以口头认可或超时未反馈替代。'].map(t=><p key={t}><CheckCircle2 size={16}/>{t}</p>)}</section></aside></div></>}
['02', '补齐材料,提交评审', '表单中简要说明业务问题和预期结果,详细内容可上传文件或关联飞书文档。', '各填写区提供对应模板,可直接查看、下载 Word,或进入飞书模板总目录创建副本。'],
['03', '评审并确认交付计划', '开发负责人默认系统管理员,无需填写。在“需求评审”由开发提出实施范围与功能说明、范围外事项,再与业务方确认。', '方案确认后进入“交付流程”:开发提出工作量、日期、优先级和设计要求,业务方确认后正式排期;需要设计稿时,另行提交业务确认。'],
['04', '开发、自测并提交验收', '开发责任人在“交付流程”记录技术方案、更新进度、管理阻塞,并提交测试版本与验收清单。', '提测需附上测试环境、数据说明、自测、代码审查和集成验证记录。业务方在“业务验收”逐项操作并明确确认;不通过则返回开发中。'],
['05', '开发发布,观察后归档', '业务验收通过后,由开发责任人完成实际部署,登记同一验收版本的发布结果,并负责生产验证。', '开发填写备份、回滚、通知和监控记录;生产验证通过、观察期结束且完成交接后,才能“交付完成并归档”。'],
['06', '处理变更、缺陷和线上故障', '范围调整在“需求变更”提出,由开发评估影响、业务方确认;未达到既定标准的问题在“缺陷”中修复和复验。', '常规修复和确认变更后重新提测验收。涉及数据恢复时,先取得业务方对目标版本、数据影响和增量保留方案的确认;新发布前须处理或撤回待确认恢复申请。'],
['07', '紧急发布后补充业务验证', '已有线上故障、规则和范围不变且无不可逆数据处理时,开发责任人可在技术验证通过后登记紧急生产发布。', '填写审查、自测、回归、备份、通知和后续验证安排;业务方按实际发布版本补充验证。通过后仍需完成生产验证、观察和交接才能归档。其他情况先完成常规业务确认与验收。'],
].map(([number, title, description, note]) => <article className="guide-step" key={number}><span>{number}</span><div><h3>{title}</h3><p>{description}</p><small>{note}</small></div></article>)}<div className="info-banner"><Info size={18}/>业务和开发使用不同账号确认。协作方提交后,关闭详情并点击“刷新需求”查看最新记录;待办按当前责任人显示。</div></section>
<aside><section className="panel guide-docs template-library"><h2><BookOpen size={20}/>配套规范与模板</h2><p className="template-library-intro">内置模板可直接阅读,也可下载后用 Word 或 WPS 填写。</p><a className="btn template-directory-link" href={FEISHU_TEMPLATE_DIRECTORY} target="_blank" rel="noopener noreferrer"><ExternalLink size={16}/>打开飞书模板总目录</a><small className="template-directory-note">使用飞书时,请先创建模板副本再填写。</small>
{documents.map(document => <div className="template-library-item" key={document.id}><h3>{document.title}</h3><p>{document.description}</p><TemplateActions documentId={document.id} showDirectory={false}/></div>)}
</section><section className="panel guide-rules"><h2>几条重要约定</h2>{['草稿是填写辅助,不属于正式流程。', '阻塞时保留当前状态,注明原因、责任人与跟进时间。', '已确认范围需要调整时,提出变更并等待双方确认。', '未达到原验收标准的问题,按缺陷处理。', '验收不能以口头认可或超时未反馈替代。'].map(text => <p key={text}><CheckCircle2 size={16}/>{text}</p>)}</section></aside>
</div>
</>;
}
+82
View File
@@ -0,0 +1,82 @@
'use client';
import { useState } from 'react';
import { CheckCircle2, CircleAlert, Send } from 'lucide-react';
import type { Demand } from '@/lib/demand';
import { currentProposal, reviewStage, type ReviewProposal } from '@/lib/demand-review';
import { pendingChange } from '@/lib/workflow';
import { AttachmentList } from './attachments';
import type { SaveInput } from './form';
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
function ProposalContent({ proposal }: { proposal: ReviewProposal }) {
return <>
<div className="detail-field"><span>实施范围与功能说明</span><p>{proposal.scope}</p></div>
<div className="detail-field"><span>范围外事项</span><p>{proposal.outOfScope}</p></div>
{(proposal.businessAttachments?.length??0)>0&&<div className="detail-field"><span>此方案评审时的附件</span><AttachmentList files={proposal.businessAttachments!}/></div>}
<p className="review-meta">由 {proposal.developer.displayName}({proposal.developer.username})提交 · {date(proposal.submittedAt)}</p>
{proposal.decision && <p className="review-meta">{proposal.decision.actor.displayName}({proposal.decision.actor.username})于 {date(proposal.decision.time)} {proposal.decision.result === 'confirmed' ? '确认同意实施' : '退回修改'}{proposal.decision.comment ? `:${proposal.decision.comment}` : ''}</p>}
{proposal.invalidated && <p className="review-invalid">此版本已失效:{proposal.invalidated.reason}({date(proposal.invalidated.time)})</p>}
</>;
}
export function DemandReviewPanel({ d, onAction, busy, onDirtyChange }: { d: Demand; onAction: (body: SaveInput) => Promise<void>; busy: boolean; onDirtyChange: (dirty: boolean) => void }) {
const proposal = currentProposal(d);
const stage = reviewStage(d);
const business = d.access?.business ?? true;
const ready = d.status === '待评审' && d.reviewReady;
const canPropose = ready && d.access?.developer && ['待开发提出方案', '待开发修改方案'].includes(stage);
const canDecide = ready && business && proposal && !proposal.invalidated && !proposal.decision;
const canReopen = ready && business && proposal && !proposal.invalidated && proposal.decision?.result === 'confirmed';
const [scope, setScope] = useState(proposal?.scope ?? d.fields.scope);
const [outOfScope, setOutOfScope] = useState(proposal?.outOfScope ?? d.fields.outOfScope);
const [comment, setComment] = useState('');
const [confirm, setConfirm] = useState(false);
const [takeoverConfirmed, setTakeoverConfirmed] = useState(false);
const [error, setError] = useState('');
function dirty() { onDirtyChange(true); setError(''); }
async function act(action: string) {
setError('');
if (action === 'propose-solution' && (!scope.trim() || !outOfScope.trim())) { setError('请填写实施范围与功能说明、范围外事项;无范围外事项请填“无”。'); return; }
if (action === 'confirm-solution' && !confirm) { setError('请勾选确认同意按当前方案实施。'); return; }
if (action === 'return-solution' && !comment.trim()) { setError('请填写具体的修改意见。'); return; }
if (action === 'take-over-development' && !takeoverConfirmed) { setError('请确认接手后的评审和排期安排。'); return; }
try { await onAction({ action, id: d.id, revision: d.revision, scope, outOfScope, proposalVersion: proposal?.version, confirm: action === 'take-over-development' ? takeoverConfirmed : confirm, comment }); } catch { /* The parent preserves input and displays the API error. */ }
}
return <section className="review-panel">
<div className="review-heading"><h2>需求评审</h2><span className={'status ' + (stage === '方案已确认' ? 'green' : 'neutral')}>{stage}</span></div>
<p className="review-intro">开发责任人提出实施范围与功能说明、范围外事项,业务方核对后确认。每次提交保留独立方案版本。</p>
{error && <div className="error-banner" role="alert"><CircleAlert size={17}/>{error}</div>}
{!d.reviewReady && <p className="info-banner">请先补齐业务材料并提交评审,开发负责人默认由系统管理员担任,无需填写。</p>}
<div className="review-assignment">
<div className="detail-field"><span>开发负责人</span><p>{d.review ? `${d.review.developer.displayName}(${d.review.developer.username})` : '系统管理员'}</p></div>
<p className="review-meta">开发负责人默认由系统管理员担任,无需填写。业务确认由需求登记账号操作;开发负责人负责方案、排期、开发提测、发布与归档。</p>
{d.access?.canTakeOverDevelopment && <fieldset className="review-assignment-form" disabled={busy}>
<p className="info-banner">原开发账号已停用或不可用,你可以使用当前管理员账号接手。接手后回到待评审,重新确认方案和排期,再提测验收;历史记录保留。</p>
{pendingChange(d) ? <p className="review-meta">请先由业务方在“需求变更”中处理或撤回待确认变更,再接手开发职责。</p> : <>
<label className="check-field"><input type="checkbox" checked={takeoverConfirmed} onChange={e => { setTakeoverConfirmed(e.target.checked); dirty(); }}/><span>我确认接手开发职责,并重新进行评审和排期。</span></label>
<button className="btn primary" onClick={() => void act('take-over-development')}>{busy ? '正在接手…' : '接手开发职责'}</button>
</>}
</fieldset>}
</div>
{(d.attachments?.length??0)>0&&<section className="review-proposal"><h3>当前参考附件</h3><AttachmentList files={d.attachments!}/></section>}
{proposal ? <section className="review-proposal"><h3>方案 v{proposal.version}</h3><ProposalContent proposal={proposal}/></section> : (d.fields.scope || d.fields.outOfScope) ? <section className="review-proposal"><h3>原有方案内容</h3><p className="review-meta">历史内容已保留,尚无本次评审确认记录。开发责任人可据此提交正式方案。</p><div className="detail-field"><span>实施范围与功能说明</span><p>{d.fields.scope || '待补充'}</p></div><div className="detail-field"><span>范围外事项</span><p>{d.fields.outOfScope || '待补充'}</p></div></section> : d.review && !canPropose ? <p className="review-intro">等待 {d.review.developer.displayName} 提交方案,提交后业务方可在此确认或退回修改。</p> : null}
{canPropose && <fieldset className="review-editor" disabled={busy}>
<h3>{proposal ? '修改并提交新版本' : '填写评审方案'}</h3>
<label className="form-field"><span>实施范围与功能说明<em>*</em></span><textarea rows={6} maxLength={6000} value={scope} onChange={e => { setScope(e.target.value); dirty(); }} placeholder="F-01:本次支持的功能、操作步骤与业务规则。"/></label>
<label className="form-field"><span>范围外事项<em>*</em></span><textarea rows={3} maxLength={3000} value={outOfScope} onChange={e => { setOutOfScope(e.target.value); dirty(); }} placeholder="明确本次不纳入的内容,无则填“无”。"/></label>
<p className="review-meta">将生成方案 v{(proposal?.version ?? 0) + 1},提交后等待业务方确认。</p>
<button className="btn primary" onClick={() => void act('propose-solution')}><Send size={16}/>{busy ? '提交中…' : '提交方案供业务确认'}</button>
</fieldset>}
{(canDecide || canReopen) && <fieldset className="review-decision" disabled={busy}>
<h3>{canReopen ? '需要调整已确认方案?' : `确认方案 v${proposal!.version}`}</h3>
<label className="form-field"><span>修改意见/确认备注</span><textarea rows={3} maxLength={3000} value={comment} onChange={e => { setComment(e.target.value); dirty(); }} placeholder="退回修改时必填;同意实施时可补充备注。"/></label>
{canDecide && <label className="check-field"><input type="checkbox" checked={confirm} onChange={e => { setConfirm(e.target.checked); dirty(); }}/><span>我已核对方案 v{proposal!.version} 的实施范围、功能说明与范围外事项,同意按此版本实施。</span></label>}
<div className="review-actions"><button className="btn" onClick={() => void act('return-solution')}>{canReopen ? '要求调整方案' : '退回修改'}</button>{canDecide && <button className="btn primary" onClick={() => void act('confirm-solution')}><CheckCircle2 size={16}/>{busy ? '提交中…' : '确认方案'}</button>}</div>
</fieldset>}
{(d.review?.proposals.length ?? 0) > 1 && <details className="review-history"><summary>历史方案({d.review!.proposals.length - 1})</summary>{d.review!.proposals.slice(0, -1).reverse().map(item => <section className="review-proposal" key={item.version}><h3>方案 v{item.version}</h3><ProposalContent proposal={item}/><details className="review-business-snapshot"><summary>当时的业务需求</summary><div className="detail-field"><span>业务背景</span><p>{item.businessFields.background}</p></div><div className="detail-field"><span>预期目标</span><p>{item.businessFields.goal}</p></div><div className="detail-field"><span>验收标准 · 文档 {item.businessFields.version}</span><p>{item.businessFields.criteria}</p></div></details></section>)}</details>}
</section>;
}
+18
View File
@@ -0,0 +1,18 @@
'use client';
import { useRef, useState } from 'react';
import { BookOpen, Download, ExternalLink } from 'lucide-react';
import { FEISHU_TEMPLATE_DIRECTORY, findDocument, templateDownloadUrl, type DocumentId } from '@/lib/documents';
import TemplatePreview from './template-preview';
export type OpenTemplatePreview = (id: DocumentId, trigger: HTMLButtonElement) => void;
export function TemplateActions({ documentId, disabled = false, showDirectory = true, onPreview }: { documentId: DocumentId; disabled?: boolean; showDirectory?: boolean; onPreview?: OpenTemplatePreview }) {
const [open, setOpen] = useState(false);
const trigger = useRef<HTMLButtonElement>(null);
const document = findDocument(documentId)!;
return <><span className="template-actions">
<button ref={trigger} className="text-button" type="button" disabled={disabled} onClick={event => { if (onPreview) onPreview(documentId, event.currentTarget); else setOpen(true); }} aria-label={'查看' + document.title}><BookOpen size={14}/>{documentId==='sop'?'查看规范':'查看模板'}</button>
<a className="text-button" href={disabled ? undefined : templateDownloadUrl(documentId)} aria-disabled={disabled || undefined} tabIndex={disabled ? -1 : undefined} download aria-label={'下载' + document.title + ' Word 版'}><Download size={14}/>{documentId==='sop'?'下载规范':'下载模板'}</a>
{showDirectory && <a className="text-button" href={disabled ? undefined : FEISHU_TEMPLATE_DIRECTORY} aria-disabled={disabled || undefined} tabIndex={disabled ? -1 : undefined} target="_blank" rel="noopener noreferrer"><ExternalLink size={14}/>飞书总目录</a>}
</span>{open && <TemplatePreview documentId={documentId} onClose={() => setOpen(false)} returnFocus={trigger}/>}</>;
}
+21
View File
@@ -0,0 +1,21 @@
'use client';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { linkedDocument, type DocumentId } from '@/lib/documents';
export type TemplateDocumentProps = { text: string; onOpenDocument: (id: DocumentId) => void };
export default function TemplateDocument({ text, onOpenDocument }: TemplateDocumentProps) {
return <article className="template-document"><Markdown remarkPlugins={[remarkGfm]} skipHtml components={{
a: ({ href, children }) => {
const related = linkedDocument(href || '');
if (related) return <button type="button" className="template-inline-link" onClick={() => onOpenDocument(related.id)}>{children}</button>;
if (!href || !/^https?:\/\//i.test(href)) return <span>{children}</span>;
return <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>;
},
img: ({ alt }) => <span>{alt ? `图片:${alt}` : '图片请查看原文档'}</span>,
pre: ({ children }) => <div className="template-text-block">{children}</div>,
table: ({ children }) => <div className="template-table-wrap"><table>{children}</table></div>,
}}>{text}</Markdown></article>;
}
+63
View File
@@ -0,0 +1,63 @@
'use client';
import { Component, useEffect, useRef, useState, type ComponentType, type ReactNode, type RefObject } from 'react';
import { ArrowLeft, Download, ExternalLink, RotateCw, X } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { FEISHU_TEMPLATE_DIRECTORY, findDocument, templateDownloadUrl, type DocumentId } from '@/lib/documents';
import { appPath } from '@/lib/base-path';
import type { TemplateDocumentProps } from './template-document';
function PreviewError({ message, onRetry }: { message: string; onRetry: () => void }) {
return <div className="error-banner template-status" role="alert"><span>{message}</span><button type="button" className="btn" onClick={onRetry}><RotateCw size={15}/>重新加载</button></div>;
}
class DocumentBoundary extends Component<{ children: ReactNode; onRetry: () => void }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() { return this.state.failed ? <PreviewError message="模板暂时无法显示,请重试。已填内容仍然保留。" onRetry={this.props.onRetry}/> : this.props.children; }
}
type PreviewContent = { id: DocumentId; text?: string; Body?: ComponentType<TemplateDocumentProps>; error?: string };
export default function TemplatePreview({ documentId, onClose, returnFocus }: { documentId: DocumentId; onClose: () => void; returnFocus: RefObject<HTMLElement | null> }) {
const [current, setCurrent] = useState(documentId);
const [history, setHistory] = useState<DocumentId[]>([]);
const [attempt, setAttempt] = useState(0);
const [content, setContent] = useState<PreviewContent | null>(null);
const scroll = useRef<HTMLDivElement>(null);
const info = findDocument(current)!;
const loading = content?.id !== current;
const Body = content?.Body;
useEffect(() => {
const controller = new AbortController();
const text = fetch(appPath('/api/documents/' + encodeURIComponent(findDocument(current)!.filename) + '?format=json'), { signal: controller.signal, cache: 'no-store' })
.then(async response => {
const result = await response.json() as { content?: string; error?: string };
if (!response.ok || typeof result.content !== 'string') throw new Error(result.error || '模板暂时无法加载,请重试。');
return result.content;
});
// Keep the dialog and form mounted even when a renderer chunk fails. Calling
// import again on retry avoids React.lazy's cached rejected promise.
const renderer = import('./template-document').catch(() => { throw new Error('模板预览未能加载,请重试。已填内容仍然保留。'); });
void Promise.all([text, renderer])
.then(([text, module]) => { if (!controller.signal.aborted) setContent({ id: current, text, Body: module.default }); })
.catch(error => {
if (controller.signal.aborted) return;
setContent({ id: current, error: error instanceof Error ? error.message : '模板加载失败,请重试。' });
controller.abort();
});
return () => controller.abort();
}, [current, attempt]);
function retry() { setContent(null); setAttempt(value => value + 1); }
function openDocument(id: DocumentId) { setHistory(previous => [...previous, current]); setCurrent(id); scroll.current?.scrollTo(0, 0); }
return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent className="demand-modal template-modal" showCloseButton={false}
onEscapeKeyDown={event => { event.preventDefault(); onClose(); }}
onCloseAutoFocus={event => { event.preventDefault(); if (returnFocus.current?.isConnected) returnFocus.current.focus({ preventScroll: true }); }}>
<div className="modal-heading"><div><DialogTitle className="modal-title">{info.title}</DialogTitle><DialogDescription className="modal-subtitle">{info.description}</DialogDescription></div><button type="button" className="icon-button" onClick={onClose} aria-label="关闭模板预览"><X size={20}/></button></div>
<div className="template-toolbar">{history.length > 0 && <button type="button" className="text-button" onClick={() => { setCurrent(history.at(-1)!); setHistory(previous => previous.slice(0, -1)); scroll.current?.scrollTo(0, 0); }}><ArrowLeft size={15}/>返回上一份模板</button>}<a className="btn" href={templateDownloadUrl(current)} download><Download size={16}/>下载 Word 版本</a><a className="text-button" href={FEISHU_TEMPLATE_DIRECTORY} target="_blank" rel="noopener noreferrer"><ExternalLink size={15}/>飞书模板总目录</a></div>
<div className="modal-scroll template-scroll" ref={scroll}>
{loading ? <p className="template-status" role="status">正在加载模板…</p> : content?.error ? <PreviewError message={content.error} onRetry={retry}/> : Body && <DocumentBoundary key={current + ':' + attempt} onRetry={retry}><Body text={content?.text || ''} onOpenDocument={openDocument}/></DocumentBoundary>}
</div>
<footer className="template-footer"><p>可以下载后用 Word 或 WPS 填写,也可以前往飞书模板总目录创建副本。</p><button type="button" className="btn primary" onClick={onClose}>返回填写</button></footer>
</DialogContent></Dialog>;
}
+94
View File
@@ -0,0 +1,94 @@
'use client';
import { useId, useState } from 'react';
import type { Demand } from '@/lib/demand';
import { currentProposal } from '@/lib/demand-review';
import { changeKey, latestRelease, pendingChange, pendingRecovery, pendingEmergencyVerification, activeIncident, designCurrent, designConfirmed, nextAcceptanceId, planCurrent, planConfirmed, type Defect } from '@/lib/workflow';
import type { SaveInput } from './form';
type Input = { key:string; label:string; type?:'textarea'|'date'|'number'|'checkbox'|'select'|'items'; options?:string[]; hint?:string };
export type ActionSpec = { action:string; title:string; description?:string; fields:Input[]; values?:Record<string,unknown>; submit?:string };
const note:Input={key:'notes',label:'处理说明',type:'textarea'};
const confirmation:Input={key:'confirm',label:'我已核对内容并确认提交',type:'checkbox'};
const decision:Input[]=[{key:'approved',label:'处理结果',type:'select',options:['同意','退回']},{key:'comment',label:'确认意见',type:'textarea'},confirmation];
const planFields:Input[]=[{key:'hours',label:'预计工作量(小时)',type:'number'},{key:'testDate',label:'计划提测日期',type:'date'},{key:'feedbackDate',label:'验收反馈截止日期',type:'date'},{key:'releaseDate',label:'计划上线日期',type:'date'},{key:'priority',label:'确认优先级',type:'select',options:['P2','P1','P0']},{key:'designRequired',label:'需要业务方确认设计稿或交互说明',type:'checkbox'},{key:'notes',label:'排期依据、依赖与风险说明',type:'textarea'}];
const planValues=(d:Demand)=>({hours:d.plan?.hours??8,testDate:d.plan?.testDate??'',feedbackDate:d.plan?.feedbackDate??'',releaseDate:d.plan?.releaseDate??'',priority:d.plan?.priority??d.fields.priority,designRequired:d.plan?.designRequired??false,notes:d.plan?.notes??''});
export function actionSpec(action:string,d:Demand,defect?:Defect):ActionSpec {
const release=latestRelease(d),change=pendingChange(d);
const common={action,title:action,fields:[] as Input[],values:{} as Record<string,unknown>};
switch(action){
case 'propose-plan':return {...common,title:'提出交付计划',description:'方案确认后,由开发责任人提出排期;业务方确认后生效。发布和生产验证由开发责任人负责。',fields:planFields,values:planValues(d)};
case 'decide-plan':return {...common,title:'确认交付计划',fields:decision,values:{planVersion:d.plan?.version,approved:true}};
case 'submit-design':return {...common,title:'提交设计确认',fields:[{key:'reference',label:'设计稿或交互说明链接'},{key:'notes',label:'设计版本、负责人及变更说明',type:'textarea'}],values:{reference:d.delivery?.design?.reference??'',notes:d.delivery?.design?.notes??''}};
case 'decide-design':return {...common,title:'确认设计',fields:decision,values:{approved:true}};
case 'start-development':return {...common,title:'开始开发',fields:[{key:'technicalPlan',label:'技术方案与代码分支',type:'textarea'},{key:'dependencies',label:'依赖、接口与开发准入检查',type:'textarea'},confirmation]};
case 'update-progress':return {...common,title:'更新开发进度',fields:[{key:'percent',label:'完成进度(%)',type:'number'},{key:'notes',label:'已完成内容与验证情况',type:'textarea'},{key:'next',label:'下一步及预计完成时间',type:'textarea'}],values:{percent:d.delivery?.progress?.percent??0}};
case 'set-blocker':return {...common,title:'标记阻塞',description:'保留当前状态,解除前暂不能推进交付。',fields:[{key:'reason',label:'阻塞原因',type:'textarea'},{key:'owner',label:'处理责任人',type:'select',options:d.review?['开发责任人','业务方']:['业务方']},{key:'dueDate',label:'计划跟进日期',type:'date'}],values:{owner:d.review?'开发责任人':'业务方'}};
case 'resolve-blocker':return {...common,title:'解除阻塞',fields:[note]};
case 'add-note':return {...common,title:'补充协作记录',fields:[{key:'notes',label:'进展、沟通结论或资料链接',type:'textarea'}]};
case 'submit-testing':return {...common,title:'提交业务验收',description:'填写可访问的测试环境、版本与验证记录,并逐项列出验收场景。请勿在说明中填写密码。',fields:[{key:'testVersion',label:'测试版本或提交号'},{key:'environment',label:'测试环境地址'},{key:'deadline',label:'验收截止日期',type:'date'},{key:'instructions',label:'操作步骤及测试数据获取方式',type:'textarea'},{key:'selfTest',label:'自测结果与记录',type:'textarea'},{key:'codeReview',label:'代码审查结论与记录',type:'textarea'},{key:'integration',label:'集成验证结果与已知问题',type:'textarea'},{key:'items',label:'验收清单',type:'items'},confirmation],values:{deadline:d.plan?.feedbackDate??'',environment:d.acceptance?.environment??'',items:d.acceptance?.documentVersion===d.fields.version?d.acceptance.items:[{id:'AC-01',feature:'F-01',scenario:'',expected:d.fields.criteria}]}};
case 'withdraw-testing':return {...common,title:'撤回交付版本',description:'回到开发中;原验收记录保留,重新提测后需重新验收。',fields:[{key:'reason',label:'代码、配置或数据变更原因',type:'textarea'}]};
case 'change':return {...common,title:'提出需求变更',description:'确认前保留原范围与计划,并暂停后续交付流转。',fields:[{key:'content',label:'变更内容',type:'textarea'},{key:'reason',label:'变更原因',type:'textarea'}]};
case 'assess-change':return {...common,title:'评估需求变更',fields:[{key:'impact',label:'工作量、设计、数据及交付风险影响',type:'textarea'},{key:'scope',label:'调整后实施范围与功能说明',type:'textarea'},{key:'outOfScope',label:'调整后范围外事项',type:'textarea'},{key:'criteria',label:'调整后验收标准',type:'textarea'},{key:'version',label:'新的需求文档版本'},...planFields],values:{...planValues(d),changeId:change&&changeKey(d,change),scope:d.fields.scope,outOfScope:d.fields.outOfScope,criteria:d.fields.criteria,version:''}};
case 'decide-change':return {...common,title:'确认需求变更',description:'同意后将采用评估中的范围、验收标准与交付计划,并重新开发、提测和验收。',fields:decision,values:{changeId:change&&changeKey(d,change),approved:true}};
case 'withdraw-change':return {...common,title:'撤回需求变更',fields:[{key:'comment',label:'撤回原因',type:'textarea'}],values:{changeId:change&&changeKey(d,change)}};
case 'report-defect':return {...common,title:'登记缺陷',fields:[{key:'title',label:'缺陷标题'},{key:'version',label:'发现版本'},{key:'steps',label:'复现步骤',type:'textarea'},{key:'expected',label:'预期结果',type:'textarea'},{key:'actual',label:'实际结果',type:'textarea'},{key:'evidence',label:'证据、截图或日志链接',type:'textarea'},{key:'blocking',label:'影响核心流程、数据或权限,阻断交付',type:'checkbox'}],values:{version:d.acceptance?.testVersion??release?.version??'',blocking:true}};
case 'start-defect':return {...common,title:'开始修复缺陷',fields:[note],values:{defectId:defect?.id}};
case 'resolve-defect':return {...common,title:'提交缺陷复验',fields:[{key:'fixVersion',label:'修复版本或提交号'},note],values:{defectId:defect?.id}};
case 'verify-defect':return {...common,title:'复验缺陷',fields:[{key:'approved',label:'复验结果',type:'select',options:['通过','不通过']},note,confirmation],values:{defectId:defect?.id,approved:true}};
case 'defer-defect':return {...common,title:'申请遗留事项',description:'仅一般问题可申请,业务方确认后才可带入发布;仍由开发责任人负责处理。',fields:[note,{key:'dueDate',label:'计划完成日期',type:'date'}],values:{defectId:defect?.id}};
case 'decide-deferral':return {...common,title:'确认遗留问题',fields:[{key:'approved',label:'处理结果',type:'select',options:['同意','退回']},note,confirmation],values:{defectId:defect?.id,approved:true}};
case 'publish':return {...common,title:'登记生产发布',description:'完成实际部署后记录版本与结果。发布版本必须与业务验收版本一致;登记后进入生产验证和观察。',fields:[{key:'version',label:'发布版本'},{key:'previousVersion',label:'上一稳定版本'},{key:'rollbackPlan',label:'回滚与恢复方案',type:'textarea'},{key:'backup',label:'备份、数据脚本和兼容性检查',type:'textarea'},{key:'deployment',label:'实际发布操作及结果',type:'textarea'},{key:'verificationPlan',label:'生产验证与监控方式',type:'textarea'},{key:'observationMinutes',label:'观察时长(分钟,至少 15)',type:'number'},{key:'testsPassed',label:'已核对业务验收、构建和测试均通过',type:'checkbox'},{key:'configurationReady',label:'配置、依赖和必要数据脚本已检查',type:'checkbox'},{key:'recoveryReady',label:'上一稳定版本、备份及恢复方式已就绪',type:'checkbox'},{key:'noticeComplete',label:'发布时间、执行人员及业务影响已通知',type:'checkbox'},confirmation],values:{version:d.acceptance?.testVersion??'',observationMinutes:30}};
case 'publish-emergency':{
const standard=actionSpec('publish',d);
return {...common,title:'登记紧急生产发布',description:'仅用于已有线上故障、业务规则与范围不变的修复。由开发责任人完成技术验证及实际部署后登记;发布后业务方必须补充验证,完成前不能归档。涉及范围、业务规则或不可逆数据处理时,请走常规评审与验收。',fields:[{key:'emergencyReason',label:'无法等待完整业务验收的原因',type:'textarea'},{key:'fixSummary',label:'修复内容及影响评估',type:'textarea'},{key:'selfTest',label:'自测与关键流程验证记录',type:'textarea'},{key:'codeReview',label:'代码审查及确认记录',type:'textarea'},{key:'integration',label:'构建、集成及关联回归记录',type:'textarea'},{key:'knownIssues',label:'已知问题及风险处理(无则填无)',type:'textarea'},{key:'followUpPlan',label:'修复同步、记录补充及后续业务验证安排',type:'textarea'},{key:'followUpDate',label:'业务验证完成日期',type:'date'},{key:'businessRulesUnchanged',label:'本次修复不调整业务规则',type:'checkbox'},{key:'scopeUnchanged',label:'本次修复不扩大已确认范围',type:'checkbox'},{key:'noIrreversibleData',label:'本次修复不涉及不可逆数据处理',type:'checkbox'},...standard.fields.map(field=>field.key==='testsPassed'?{...field,label:'自测、代码审查、构建及关联回归均通过'}:field)],values:{version:'',previousVersion:release?.rollback?.runningVersion??release?.version??'',observationMinutes:30}};
}
case 'verify-emergency':{const pending=pendingEmergencyVerification(d);return {...common,title:'补充紧急发布业务验证',description:`核对紧急发布版本 ${pending?.version??''} 的实际业务结果;本次结论只关联该发布记录。`,fields:[{key:'approved',label:'业务验证结果',type:'select',options:['通过','不通过']},{key:'comment',label:'验证结果、证据与问题说明',type:'textarea'},confirmation],values:{releaseId:pending?.id,approved:true}};}
case 'verify-production':return {...common,title:'记录生产验证',fields:[{key:'approved',label:'验证结果',type:'select',options:['通过','不通过']},{key:'results',label:'核心功能、数据与监控验证结果',type:'textarea'},confirmation],values:{approved:true}};
case 'complete':return {...common,title:'交付完成并归档',description:'生产验证通过、约定观察期结束且交接完成后,才能归档。',fields:[{key:'summary',label:'观察结论与交付总结',type:'textarea'},{key:'handover',label:'交接资料及业务通知记录',type:'textarea'},{key:'monitoring',label:'监控、故障联系人和告警渠道',type:'textarea'},confirmation]};
case 'request-recovery':return {...common,title:'申请数据恢复确认',description:'涉及恢复数据前,由业务方确认影响及新增数据的保留方案。',fields:[{key:'targetVersion',label:'恢复目标版本'},{key:'dataImpact',label:'对现有业务数据的影响',type:'textarea'},{key:'plan',label:'数据恢复与增量保留方案',type:'textarea'}],values:{targetVersion:release?.previousVersion??''}};
case 'decide-recovery':return {...common,title:'确认数据恢复方案',description:`发布版本 ${pendingRecovery(d)?.version??''};恢复目标 ${pendingRecovery(d)?.recoveryRequest?.targetVersion??''}。已被新发布替代的旧申请须退回后重新申请。`,fields:decision,values:{releaseId:pendingRecovery(d)?.id,approved:true}};
case 'withdraw-recovery':return {...common,title:'撤回数据恢复申请',description:'撤回仅结束该申请,不执行数据恢复。后续需要恢复时须重新申请确认。',fields:[{key:'reason',label:'撤回原因',type:'textarea'}],values:{releaseId:pendingRecovery(d)?.id}};
case 'rollback':return {...common,title:'登记回滚与恢复',description:'记录实际恢复结果,需求返回开发中,修复后重新提测和验收。',fields:[{key:'reason',label:'回滚原因与影响',type:'textarea'},{key:'runningVersion',label:'恢复后的实际运行版本'},{key:'dataRestored',label:'此次恢复涉及业务数据(须先取得业务确认)',type:'checkbox'},{key:'verification',label:'恢复后的核心功能与数据验证',type:'textarea'},confirmation],values:{runningVersion:release?.previousVersion??'',dataRestored:false}};
case 'reopen-incident':return {...common,title:'登记线上故障并启动修复',description:'用于已上线需求在既有范围内的缺陷修复;新增业务目标请另行登记需求。',fields:[{key:'impact',label:'线上故障及影响范围',type:'textarea'},{key:'reason',label:'既有范围内需要修复的内容',type:'textarea'},confirmation]};
case 'retrospective':return {...common,title:'记录复盘与改进',fields:[{key:'cause',label:'原因分析',type:'textarea'},{key:'actions',label:'改进措施',type:'textarea'},{key:'owner',label:'改进责任人'},{key:'dueDate',label:'计划完成日期',type:'date'}]};
default:throw new Error('未知流程操作');
}
}
export function WorkflowForm({ spec,d,onAction,onClose,onDirtyChange,busy }: { spec:ActionSpec;d:Demand;onAction:(body:SaveInput)=>Promise<void>;onClose:()=>void;onDirtyChange:(dirty:boolean)=>void;busy:boolean }) {
const prefix=useId();const [values,setValues]=useState<Record<string,unknown>>(()=>({...spec.values}));const [dirty,setDirty]=useState(false);const [leaving,setLeaving]=useState(false);
function set(key:string,value:unknown){setValues(previous=>({...previous,[key]:value}));setDirty(true);onDirtyChange(true);}
async function submit(event:React.FormEvent){event.preventDefault();try{await onAction({action:spec.action,id:d.id,revision:d.revision,...values});onDirtyChange(false);onClose();}catch{ /* Parent reports errors while this form retains its input. */ }}
const items=(values.items??[]) as {id:string;feature:string;scenario:string;expected:string}[];
return <form className="workflow-form" onSubmit={submit}><h2>{spec.title}</h2>{spec.description&&<p className="workflow-help">{spec.description}</p>}<fieldset disabled={busy} className="workflow-fields">{spec.fields.map(field=>{
const id=prefix+'-'+field.key;
if(field.type==='checkbox')return <label className="check-field" key={id}><input id={id} type="checkbox" checked={values[field.key]===true} onChange={e=>set(field.key,e.target.checked)}/><span>{field.label}</span></label>;
if(field.type==='items')return <div className="testing-items" key={id}><h3>{field.label}</h3>{items.map((item,index)=><fieldset className="testing-item" key={index}><legend>验收项 {index+1}</legend>{(['id','feature','scenario','expected'] as const).map((key,i)=><label className="form-field" key={key}><span>{['编号','关联功能','场景与操作','预期结果'][i]}</span><textarea aria-label={`验收项 ${index+1} ${['编号','关联功能','场景与操作','预期结果'][i]}`} rows={key==='scenario'||key==='expected'?3:1} required value={item[key]} onChange={e=>set('items',items.map((row,j)=>j===index?{...row,[key]:e.target.value}:row))}/></label>)}<button type="button" className="text-button danger-text" disabled={items.length<=1} onClick={()=>set('items',items.filter((_,j)=>j!==index))}>移除此验收项</button></fieldset>)}<button className="btn" type="button" disabled={items.length>=100} onClick={()=>set('items',[...items,{id:nextAcceptanceId(items),feature:'',scenario:'',expected:''}])}>添加验收项</button></div>;
const isDecision=field.key==='approved';
return <label className="form-field" key={id} htmlFor={id}><span>{field.label}<em>*</em></span>{field.type==='select'?<select id={id} value={isDecision?(values.approved===false?'1':'0'):String(values[field.key]??field.options?.[0]??'')} onChange={e=>set(field.key,isDecision?e.target.value==='0':e.target.value)}>{field.options?.map((option,index)=><option key={option} value={isDecision?String(index):option}>{option}</option>)}</select>:field.type==='textarea'?<textarea id={id} rows={3} required value={String(values[field.key]??'')} maxLength={field.key==='scope'||field.key==='criteria'?6000:5000} onChange={e=>set(field.key,e.target.value)}/>:<input id={id} type={field.type??'text'} step={field.key==='hours'?'0.5':'1'} required value={String(values[field.key]??'')} maxLength={2000} onChange={e=>set(field.key,field.type==='number'?(e.target.value===''?'':Number(e.target.value)):e.target.value)}/>}</label>;
})}</fieldset><div className="workflow-form-actions">{leaving&&<div className="workflow-leave" role="alert"><p>返回将放弃本次未保存的输入。</p><button type="button" className="btn" onClick={()=>setLeaving(false)}>继续填写</button><button type="button" className="btn danger-button" onClick={onClose}>放弃输入并返回</button></div>}<button type="button" className="btn" disabled={busy} onClick={()=>dirty?setLeaving(true):onClose()}>返回当前记录</button><button className="btn primary" disabled={busy}>{busy?'正在保存…':spec.submit??spec.title}</button></div></form>;
}
export function availableDeliveryActions(d:Demand):string[]{
const business=d.access?.business??true,developer=Boolean(d.access?.developer),actions:string[]=[];
if(!business&&!developer||['草稿','已取消'].includes(d.status))return actions;
const confirmed=currentProposal(d)?.decision?.result==='confirmed'&&!currentProposal(d)?.invalidated;
if(developer&&confirmed&&['待评审','已排期','开发中'].includes(d.status))actions.push('propose-plan');
if(business&&planCurrent(d)&&d.plan?.proposedAt&&!d.plan.decision)actions.push('decide-plan');
if(developer&&planConfirmed(d)&&d.plan?.designRequired&&['已排期','开发中'].includes(d.status))actions.push('submit-design');
if(business&&designCurrent(d)&&d.delivery?.design&&!d.delivery.design.decision&&['已排期','开发中'].includes(d.status))actions.push('decide-design');
if(developer&&d.status==='已排期'&&planConfirmed(d)&&(!d.plan?.designRequired||designConfirmed(d)))actions.push('start-development');
if(developer&&d.status==='开发中')actions.push('update-progress','submit-testing');
if(developer&&['待验收','待发布'].includes(d.status))actions.push('withdraw-testing');
if(developer&&d.status==='待发布')actions.push('publish');
if(developer&&activeIncident(d)&&confirmed&&['开发中','待验收','待发布'].includes(d.status)&&latestRelease(d)?.documentVersion===d.fields.version&&latestRelease(d)?.proposalVersion===currentProposal(d)?.version)actions.push('publish-emergency');
if(business&&pendingEmergencyVerification(d))actions.push('verify-emergency');
if(developer&&d.status==='已上线')actions.push('verify-production','complete');
if(latestRelease(d)&&!latestRelease(d)?.rollback&&developer){if(!pendingRecovery(d))actions.push('request-recovery');actions.push('rollback');}
if(pendingRecovery(d)){if(business)actions.push('decide-recovery');if(developer)actions.push('withdraw-recovery');}
if(developer&&['已上线','已完成'].includes(d.status))actions.push('reopen-incident');
if(developer)actions.push('retrospective');
if(d.status!=='已完成')actions.push(d.blocked?'resolve-blocker':'set-blocker');
actions.push('add-note');return actions;
}
+42
View File
@@ -0,0 +1,42 @@
'use client';
import { useState } from 'react';
import type { Demand } from '@/lib/demand';
import { pendingChange, pendingRecovery, pendingEmergencyVerification, designCurrent, planCurrent, planConfirmed, workflowTask, type ChangeRecord, type Defect, type DeliveryPlan } from '@/lib/workflow';
import type { SaveInput } from './form';
import { actionSpec, availableDeliveryActions, WorkflowForm, type ActionSpec } from './workflow-actions';
const date=(value?:string)=>value?new Date(value).toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false}):'待填写';
function Field({label,value}:{label:string;value:unknown}){return <div className="detail-field"><span>{label}</span><p>{String(value??'未记录')}</p></div>;}
function Plan({plan}:{plan:DeliveryPlan}){return <><div className="workflow-grid"><Field label="开发与发布责任人" value={plan.developer}/><Field label="预计工作量" value={plan.hours===undefined?'历史计划':`${plan.hours} 小时`}/><Field label="提测日期" value={plan.testDate}/><Field label="验收反馈截止" value={plan.feedbackDate}/><Field label="上线日期" value={plan.releaseDate}/><Field label="优先级与设计要求" value={`${plan.priority??'未记录'} · ${plan.designRequired?'需确认设计':'无需单独设计'}`}/></div><Field label="计划说明" value={plan.notes}/><p className="review-meta">{plan.proposedBy?.displayName} {date(plan.proposedAt)} 提出{plan.decision?`;${plan.decision.actor.displayName} ${plan.decision.approved?'确认':'退回'}:${plan.decision.comment}`:';等待业务方确认'}</p></>;}
function Change({change}:{change:ChangeRecord}){return <section className="workflow-record"><div className="workflow-record-heading"><h3>{change.content}</h3><span className="status neutral">{change.status}</span></div><Field label="变更原因" value={change.reason}/><p className="review-meta">{change.actor} · {date(change.time)} · 原文档 {change.originalVersion}</p>{change.assessment&&<><Field label="影响评估" value={change.assessment.impact}/><Field label="调整后范围" value={change.assessment.fields.scope}/><Field label="调整后范围外事项" value={change.assessment.fields.outOfScope}/><Field label={`验收标准 · ${change.assessment.fields.version}`} value={change.assessment.fields.criteria}/><Plan plan={{...change.assessment.plan,decision:change.decision??change.assessment.plan.decision}}/></>}{change.decision&&<p className="review-meta">{change.decision.actor.displayName} · {date(change.decision.time)}:{change.decision.comment}</p>}<details><summary>查看变更前业务内容</summary>{change.originalFields&&Object.entries(change.originalFields).filter(([key])=>['background','goal','scope','outOfScope','criteria'].includes(key)).map(([key,value])=><Field key={key} label={({background:'业务背景',goal:'目标',scope:'实施范围',outOfScope:'范围外事项',criteria:'验收标准'} as Record<string,string>)[key]} value={value}/>)}</details></section>;}
export function WorkflowPanel({d,kind,onAction,busy,onDirtyChange}:{d:Demand;kind:'delivery'|'changes'|'defects';onAction:(body:SaveInput)=>Promise<void>;busy:boolean;onDirtyChange:(dirty:boolean)=>void}){
const [spec,setSpec]=useState<ActionSpec|null>(null);
const active=!['草稿','已取消'].includes(d.status);
const business=(d.access?.business??true)&&active,developer=Boolean(d.access?.developer)&&active,participant=business||developer;
const open=(action:string,defect?:Defect)=>setSpec(actionSpec(action,d,defect));
const button=(action:string,label?:string)=><button type="button" className="btn" disabled={busy} key={action} onClick={()=>open(action)}>{label??actionSpec(action,d).title}</button>;
if(spec)return <WorkflowForm key={spec.action+String(spec.values?.defectId??'')} spec={spec} d={d} onAction={onAction} busy={busy} onDirtyChange={onDirtyChange} onClose={()=>{setSpec(null);onDirtyChange(false);}}/>;
const flow=d.delivery,recovery=pendingRecovery(d),emergency=pendingEmergencyVerification(d),change=pendingChange(d);
if(kind==='changes')return <section><div className="workflow-heading"><h2>需求变更</h2>{business&&['已排期','开发中','待验收','待发布','已上线'].includes(d.status)&&!change&&button('change')}</div>{change&&<div className="workflow-callout"><p>当前变更待处理,后续交付流转暂时停止。</p><div className="workflow-buttons">{developer&&change.status!=='待业务确认'&&button('assess-change')}{business&&change.status==='待业务确认'&&button('decide-change')}{business&&button('withdraw-change')}</div></div>}{d.changes.length?[...d.changes].reverse().map((item,i)=><Change key={item.id??i} change={item}/>):<p className="workflow-help">暂无需求变更。需要调整已确认的范围或验收标准时,在这里提出并保留双方确认记录。</p>}</section>;
if(kind==='defects')return <section><div className="workflow-heading"><h2>缺陷与遗留事项</h2>{participant&&!['草稿','已取消'].includes(d.status)&&button('report-defect')}</div>{!flow?.defects?.length&&<p className="workflow-help">暂无缺陷。未达到已确认验收标准的问题,在这里登记、修复及复验。</p>}{[...(flow?.defects??[])].reverse().map(defect=><section className="workflow-record" key={defect.id}><div className="workflow-record-heading"><h3>{defect.id} · {defect.title}</h3><span className={'status '+(defect.status==='已关闭'?'green':'neutral')}>{defect.status}</span></div><p className="review-meta">{defect.blocking?'阻断交付':'一般问题'} · {defect.version} · {defect.reporter.displayName} · {date(defect.time)}</p><Field label="复现步骤" value={defect.steps}/><Field label="预期结果" value={defect.expected}/><Field label="实际结果" value={defect.actual}/><Field label="证据与日志" value={defect.evidence}/>{defect.resolution&&<Field label="修复或遗留处理说明" value={defect.resolution}/>}<div className="workflow-grid">{defect.fixVersion&&<Field label="修复版本" value={defect.fixVersion}/>}<Field label="处理责任人" value={d.review?.developer.displayName??'系统管理员'}/>{defect.dueDate&&<Field label="计划完成日期" value={defect.dueDate}/>}</div><div className="workflow-buttons">{developer&&['待处理','已确认遗留'].includes(defect.status)&&<button className="btn" disabled={busy} onClick={()=>open('start-defect',defect)}>开始修复</button>}{developer&&['待处理','修复中','已确认遗留'].includes(defect.status)&&<button className="btn" disabled={busy} onClick={()=>open('resolve-defect',defect)}>提交复验</button>}{developer&&!defect.blocking&&['待处理','修复中'].includes(defect.status)&&<button className="btn" disabled={busy} onClick={()=>open('defer-defect',defect)}>申请遗留</button>}{business&&defect.status==='待复验'&&<button className="btn primary" disabled={busy} onClick={()=>open('verify-defect',defect)}>复验缺陷</button>}{business&&defect.status==='待确认遗留'&&<button className="btn primary" disabled={busy} onClick={()=>open('decide-deferral',defect)}>确认遗留问题</button>}</div>{defect.events.length>0&&<details><summary>处理记录({defect.events.length})</summary>{defect.events.map((event,i)=><p className="workflow-event" key={i}>{date(event.time)} · {event.actor.displayName} · {event.action}<br/>{event.notes}</p>)}</details>}</section>)}</section>;
return <section>
<div className="workflow-heading"><h2>交付流程</h2><span className="status blue">{d.status}</span></div>
{workflowTask(d)&&<p className="workflow-help">当前待办:{workflowTask(d)}</p>}
{d.blocked&&<div className="workflow-callout"><strong>当前阻塞:{d.blocked}</strong><p>{flow?.blocker?.owner} · 计划跟进 {flow?.blocker?.dueDate??'待补充'}</p></div>}
{change&&<p className="workflow-callout">存在待处理需求变更,请在“需求变更”中完成评估与确认。</p>}
<div className="workflow-buttons">{availableDeliveryActions(d).map(action=>button(action))}</div>
<section className="workflow-record"><div className="workflow-record-heading"><h3>交付计划{d.plan?.version?` v${d.plan.version}`:''}</h3>{d.plan&&<span className="status neutral">{!planCurrent(d)?'历史计划,需重新确认':planConfirmed(d)?'已确认':d.plan.decision?.approved===false?'已退回':'待确认'}</span>}</div>{d.plan?<Plan plan={d.plan}/>:<p className="workflow-help">方案确认后,由开发责任人提出工作量、优先级和计划日期,再由业务方确认。</p>}</section>
{flow?.design&&<section className="workflow-record"><h3>设计与交互确认</h3><Field label="设计资料" value={flow.design.reference}/><Field label="设计说明" value={flow.design.notes}/><p className="review-meta">{!designCurrent(d)?'历史设计,需针对当前方案重新提交确认':flow.design.decision?`${flow.design.decision.approved?'已确认':'已退回'} · ${flow.design.decision.actor.displayName}:${flow.design.decision.comment}`:'等待业务方确认'}</p></section>}
{flow?.kickoff&&<section className="workflow-record"><h3>开发准入与技术方案</h3><Field label="技术方案与代码分支" value={flow.kickoff.technicalPlan}/><Field label="依赖与接口检查" value={flow.kickoff.dependencies}/><p className="review-meta">{flow.kickoff.actor.displayName} · {date(flow.kickoff.time)}</p></section>}
{flow?.progress&&<section className="workflow-record"><h3>开发进度 · {flow.progress.percent}%</h3><Field label="进展" value={flow.progress.notes}/><Field label="下一步" value={flow.progress.next}/><p className="review-meta">{flow.progress.actor.displayName} · {date(flow.progress.time)}</p></section>}
{!!flow?.testing?.length&&<section className="workflow-record"><h3>提测与验证记录</h3>{[...flow.testing].reverse().map((round,i)=><details key={round.round??i} open={i===0}><summary>第 {round.round} 轮 · {round.testVersion} · 文档 {round.documentVersion}{round.withdrawnAt?' · 已撤回':''}</summary><Field label="自测结果" value={round.selfTest}/><Field label="代码审查" value={round.codeReview}/><Field label="集成验证" value={round.integration}/><Field label="测试环境" value={round.environment}/><Field label="测试数据与操作说明" value={round.instructions}/><p className="review-meta">{round.actor?.displayName} · {date(round.time)} · 验收截止 {round.deadline}</p></details>)}</section>}
{recovery?.recoveryRequest&&<section className="workflow-callout"><h3>待业务确认的数据恢复申请 · {recovery.version}</h3><Field label="恢复目标版本" value={recovery.recoveryRequest.targetVersion}/><Field label="业务数据影响" value={recovery.recoveryRequest.dataImpact}/><Field label="恢复及增量保留方案" value={recovery.recoveryRequest.plan}/></section>}
{emergency?.emergency&&<section className="workflow-callout"><h3>紧急发布待补充业务验证 · {emergency.version}</h3><Field label="验证完成日期" value={emergency.emergency.followUpDate}/><Field label="修复同步与业务验证安排" value={emergency.emergency.followUpPlan}/></section>}
{!!flow?.releases?.length&&<section className="workflow-record"><h3>发布、观察与归档</h3>{[...flow.releases].reverse().map((item,i)=><details key={item.id} open={i===0}><summary>{item.emergency?'紧急发布 · ':''}{item.version} · {date(item.time)} · {item.rollback?'已回滚':item.completion?'已归档':'已发布'}</summary><Field label="上一稳定版本" value={item.previousVersion}/><Field label="实际发布记录" value={item.deployment}/><Field label="备份与兼容性检查" value={item.backup}/><Field label="恢复方案" value={item.rollbackPlan}/><Field label="生产验证与监控计划" value={item.verificationPlan}/><Field label="约定观察结束时间" value={date(item.observeUntil)}/>{item.emergency&&<><Field label="紧急发布原因" value={item.emergency.reason}/><Field label="修复内容及影响评估" value={item.emergency.fixSummary}/><Field label="自测与关键流程验证" value={item.emergency.selfTest}/><Field label="代码审查" value={item.emergency.codeReview}/><Field label="构建、集成与回归" value={item.emergency.integration}/><Field label="已知问题及风险处理" value={item.emergency.knownIssues}/><Field label="修复同步与后续验证安排" value={item.emergency.followUpPlan}/><Field label="业务验证完成日期" value={item.emergency.followUpDate}/><Field label="补充业务验证结果" value={item.emergency.followUp?`${item.emergency.followUp.approved?'通过':'不通过'} · ${item.emergency.followUp.actor.displayName} · ${date(item.emergency.followUp.time)};${item.emergency.followUp.comment}`:item.rollback?'发布已回滚':'待业务方补充验证'}/></>}{item.verification&&<Field label={item.verification.passed?'生产验证通过':'生产验证未通过'} value={item.verification.results}/>} {item.recoveryRequest&&<><Field label="数据恢复目标与方案" value={item.recoveryRequest.targetVersion+';'+item.recoveryRequest.plan}/><Field label="数据影响" value={item.recoveryRequest.dataImpact}/><Field label="业务恢复确认" value={item.recoveryRequest.withdrawn?'已撤回 · '+item.recoveryRequest.withdrawn.actor.displayName+':'+item.recoveryRequest.withdrawn.reason:item.recoveryRequest.decision?`${item.recoveryRequest.decision.approved?'已确认':'未同意'} · ${item.recoveryRequest.decision.actor.displayName}:${item.recoveryRequest.decision.comment}`:'待业务确认'}/></>}{item.rollback&&<><Field label="回滚原因" value={item.rollback.reason}/><Field label="实际运行版本及恢复验证" value={item.rollback.runningVersion+';'+item.rollback.verification}/></>}{item.completion&&<><Field label="交付总结" value={item.completion.summary}/><Field label="交接与通知记录" value={item.completion.handover}/><Field label="监控与故障联系" value={item.completion.monitoring}/></>}<p className="review-meta">开发与发布责任人:{item.actor.displayName}</p></details>)}</section>}
{!!flow?.plans?.length&&<details className="workflow-record"><summary>历史交付计划({flow.plans.length})</summary>{[...flow.plans].reverse().map((plan,i)=><section className="workflow-record" key={i}><h3>计划 v{plan.version??'历史'}</h3><Plan plan={plan}/></section>)}</details>}
{!!flow?.designHistory?.length&&<details className="workflow-record"><summary>历史设计记录({flow.designHistory.length})</summary>{flow.designHistory.map((item,i)=><Field key={i} label={`${item.actor.displayName} · ${date(item.time)}`} value={item.reference+';'+item.notes+';'+(item.decision?.comment??'未确认')}/>)}</details>}
{!!flow?.incidents?.length&&<section className="workflow-record"><h3>线上故障记录</h3>{flow.incidents.map(item=><Field key={item.id} label={`${item.actor.displayName} · ${date(item.time)}`} value={item.impact+';'+item.reason}/>)}</section>}
{!!flow?.retrospectives?.length&&<section className="workflow-record"><h3>复盘与改进</h3>{flow.retrospectives.map((item,i)=><div key={i}><Field label="原因与改进措施" value={item.cause+';'+item.actions}/><p className="review-meta">{item.owner} · 计划完成 {item.dueDate} · {date(item.time)}</p></div>)}</section>}
</section>;
}
+45
View File
@@ -0,0 +1,45 @@
name: xuyouxu-demand-center
services:
app:
build:
context: .
dockerfile: Dockerfile
args:
NEXT_PUBLIC_BASE_PATH: ${NEXT_PUBLIC_BASE_PATH:-}
init: true
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
environment:
NODE_ENV: production
HOSTNAME: 0.0.0.0
PORT: "3000"
DATA_DIR: /app/data
NEXT_PUBLIC_BASE_PATH: ${NEXT_PUBLIC_BASE_PATH:-}
APP_URL: ${APP_URL:?请在 .env 中设置 APP_URL}
LOGIN_CLIENT_IP_HEADER: ${LOGIN_CLIENT_IP_HEADER:-}
INITIAL_ADMIN_USERNAME: ${INITIAL_ADMIN_USERNAME:?请在 .env 中设置初始管理员用户名}
INITIAL_ADMIN_PASSWORD: ${INITIAL_ADMIN_PASSWORD:?请在 .env 中设置至少 12 位的初始管理员密码}
FEISHU_APP_ID: ${FEISHU_APP_ID:-}
FEISHU_APP_SECRET: ${FEISHU_APP_SECRET:-}
FEISHU_TENANT_KEY: ${FEISHU_TENANT_KEY:-}
FEISHU_BOT_WEBHOOK: ${FEISHU_BOT_WEBHOOK:-}
FEISHU_BOT_SECRET: ${FEISHU_BOT_SECRET:-}
INITIAL_ADMIN_DISPLAY_NAME: ${INITIAL_ADMIN_DISPLAY_NAME:-系统管理员}
volumes:
- demand_data:/app/data
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000'+(process.env.NEXT_PUBLIC_BASE_PATH||'')+'/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
demand_data:
@@ -18,12 +18,12 @@
| 角色 | 主要职责 | 主要交付或确认事项 |
|---|---|---|
| 需求负责人 | 组织需求登记、编制并维护需求文档,明确业务目标、范围与优先级,汇总业务意见并组织验收 | 需求记录及文档、验收标准、设计确认、业务验收结论 |
| 需求负责人 | 组织需求登记、编制并维护需求文档,明确业务目标与优先级,在评审时确认开发责任人提出的方案,汇总业务意见并组织验收 | 需求记录及文档、验收标准、设计确认、业务验收结论 |
| 设计负责人 | 制定界面与交互方案、维护设计版本、落实评审意见 | 设计稿、交互说明、设计变更记录 |
| 开发负责人 | 评估工作量与风险,制定技术方案,实施开发、自测及缺陷修复,维护技术说明,组织代码审查与验证并确认技术交付条件 | 开发计划、技术方案及说明、代码变更、自测记录、审查与验证结论、缺陷修复结果 |
| 开发负责人 | 在需求评审时提出实施范围、功能说明及范围外事项,并与业务方确认;评估工作量与风险,制定技术方案,实施开发、自测及缺陷修复,维护技术说明,组织代码审查与验证并确认技术交付条件 | 评审方案及双方确认记录、开发计划、技术方案及说明、代码变更、自测记录、审查与验证结论、缺陷修复结果 |
| 发布与运维负责人 | 执行版本发布、组织生产验证、开展运行监控、实施故障恢复 | 发布记录、观察结果、故障及恢复记录 |
责任角色及人员安排应在项目或需求记录中明确。涉及多个业务参与方时,由需求负责人统一汇总反馈并形成业务确认结论。故障处理负责人及联系渠道应在发布前确定。
本规范中的开发负责人即需求对应的开发责任人,默认由系统管理员担任,无需手动填写。其他责任角色及人员安排应在项目或需求记录中明确。涉及多个业务参与方时,由需求负责人统一汇总反馈并形成业务确认结论。故障处理负责人及联系渠道应在发布前确定。
## 三、流程与状态管理
@@ -62,7 +62,7 @@
#### 4.1.1 登记责任与方式
需求应登记至统一使用的需求管理工具或共享台账。提出人提供原始诉求及业务依据,需求负责人负责核实、登记、补充和维护;开发负责人负责技术评估、工作量及交付计划的填写与确认。
需求应登记至统一使用的需求管理工具或共享台账。提出人提供原始诉求及业务依据,需求负责人负责核实、登记、补充和维护;开发负责人在需求评审时提出实施范围与功能说明、范围外事项,并与业务方确认,同时负责技术评估、工作量及交付计划的填写与确认。
1. 登记前应查询已有需求;同一目标的重复诉求应合并至原记录,并补充来源及影响范围。
2. 每条需求应对应一个可独立评审和验收的业务目标。涉及多个独立目标的,应拆分登记;属于同一项目的,可通过主需求与子需求关联。
@@ -80,13 +80,13 @@
| 业务背景及影响对象 | 说明现有处理方式、存在的问题、受影响的用户或岗位,提供数据、案例或操作截图作为依据 | 登记时 |
| 预期目标 | 说明实施后需要实现的业务结果;具备量化依据的,填写目标值及统计口径,不应将未经验证的估计作为事实 | 登记时 |
| 期望上线时间及依据 | 填写业务期望日期及原因,如业务节点或外部依赖;无固定日期的注明“无固定日期” | 登记时 |
| 实施范围与范围外事项 | 列出本次功能清单及明确不纳入本次交付的内容 | 提交评审前 |
| 验收标准 | 按功能列出可验证的预期结果,覆盖主要流程及关键异常 | 提交评审前 |
| 实施范围与功能说明、范围外事项 | 由开发责任人提出方案,说明本次功能、操作及规则和不纳入本次交付的内容,并与业务方确认 | 需求评审时 |
| 验收标准 | 按业务场景列出可验证的预期结果,覆盖主要流程及关键异常;评审时结合方案确认并关联功能编号 | 提交评审前 |
| 建议优先级及依据 | 提出P0、P1或P2建议,说明业务影响、时间要求及依赖;最终优先级由评审确认 | 提交评审前 |
| 数据来源及联系人 | 写明数据平时从哪个系统、页面、报表或文件中获取,或由谁填写、提供;详细说明可放在需求文档中 | 提交评审前 |
| 依赖、风险及待确认事项 | 明确外部系统、数据、人员配合及未决问题,并注明处理责任人和计划确认时间;无相关事项的填“无” | 提交评审前 |
| 需求文档及参考材料 | 关联需求文档的当前版本、原型、截图或业务规则;直接使用需求记录承载正文的,注明修订日期 | 提交评审前 |
| 开发负责人及交付计划 | 填写负责人、预计工作量、提测时间、验收反馈截止时间及计划上线时间 | 进入“已排期”前 |
| 开发负责人及交付计划 | 开发负责人默认系统管理员,无需填写;填写预计工作量、提测时间、验收反馈截止时间及计划上线时间 | 进入“已排期”前 |
| 状态及过程记录 | 更新当前状态、阻塞事项及设计、代码、验收、发布等记录链接 | 随进度更新 |
业务期望上线时间用于评估优先级,不直接构成交付承诺。正式交付计划由需求负责人和开发负责人评审确认后填写。
@@ -111,9 +111,9 @@
#### 4.3.1 编制责任与文档形式
需求负责人负责业务内容的编写及维护,设计负责人补充界面与交互说明,开发负责人补充技术约束、风险和工作量评估。业务规则与验收标准应由需求负责人确认。
需求负责人负责业务内容的编写及维护,设计负责人补充界面与交互说明,开发负责人在需求评审时编写实施范围、功能清单及详细说明、范围外事项,并与业务方确认,同时补充技术约束、风险和工作量评估。业务规则与验收标准应由需求负责人确认。
- **简单需求**:规则明确、影响范围有限且易于恢复,通常可在1~2个工作日内完成的,可直接在需求记录中填写背景、范围、具体规则、相关异常及验收标准,无需重复编制独立文档。
- **简单需求**:规则明确、影响范围有限且易于恢复,通常可在1~2个工作日内完成的,可直接在需求记录中填写背景、业务规则、相关异常及验收标准;实施范围与功能说明、范围外事项由开发责任人在评审时补充并与业务方确认,无需重复编制独立文档。
- **复杂需求**:涉及多个流程、跨系统协作、较多业务规则或明显不确定性的,应编制独立需求说明文档(PRD),按本节结构填写。
- **高风险变更**:影响资金处理、权限边界、敏感数据处理,或涉及批量数据修改、不可逆操作及重要架构调整的,应增加风险评估、验证方法和恢复方案,不以预计开发时长作为简化依据。
@@ -126,9 +126,9 @@
| 基本信息 | 需求编号、标题、文档版本、编写人、需求负责人、更新日期及确认状态 |
| 背景与目标 | 当前业务流程、具体问题、影响对象、实施必要性及预期结果;量化目标应注明依据和统计口径 |
| 使用角色与场景 | 实际使用者、触发需求的业务场景、使用入口及必要前置条件 |
| 实施范围与功能清单 | 本次交付的功能及范围外事项;功能按`F-01`、`F-02`等编号,注明名称和预期结果 |
| 实施范围与功能清单 | 需求评审时由开发责任人提出本次交付的功能及范围外事项,并与业务方确认;功能按`F-01`、`F-02`等编号,注明名称和预期结果 |
| 业务流程 | 正常处理顺序、判断条件、角色交接及结束条件;涉及状态流转的,明确允许的流转和限制条件 |
| 功能详细说明 | 按4.3.3逐项填写输入、操作、处理规则、输出、异常和权限要求 |
| 功能详细说明 | 需求评审时由开发责任人按4.3.3逐项提出输入、操作、处理规则、输出、异常和权限方案,并与业务方确认 |
| 数据来源说明 | 由业务方按4.3.6说明数据从哪里来、由谁提供、需要哪些内容、多久更新,以及数据不一致时以哪个来源为准 |
| 数据与权限 | 需要填写、展示或导出的内容及填写限制,以及哪些人员可以查看或修改 |
| 其他约束 | 按实际需要说明性能、兼容性、数据量、历史数据处理等要求;不适用的可注明原因 |
@@ -138,7 +138,7 @@
#### 4.3.3 单项功能填写要求
每项功能应单独说明,内容应达到可开展设计、开发和验收的程度。相关规则可通过表格、流程图或文字表达。
需求评审时,由开发责任人根据业务诉求逐项提出功能方案,并与业务方确认。每项功能应单独说明,内容应达到可开展设计、开发和验收的程度。相关规则可通过表格、流程图或文字表达。
| 说明项 | 填写要求 |
|---|---|
@@ -221,25 +221,24 @@
提交评审前,需求负责人应完成以下检查:
- [ ] 基本信息、业务背景、目标和需求负责人填写完整。
- [ ] 本次范围与范围外事项明确,功能清单与详细说明一致。
- [ ] 关键输入、业务规则、权限及异常处理已说明。
- [ ] 已知业务规则、权限要求及关键异常场景已说明,供开发责任人制定方案。
- [ ] 涉及数据的,已说明来源、所需内容、提供联系人和更新要求,并附样例;暂未提供的,已明确提供人和时间。
- [ ] 各项功能有对应验收标准,验收结果可判断。
- [ ] 主要业务场景有可验证的验收标准,评审时再与功能方案建立对应关系。
- [ ] 参考材料可访问且版本明确,待确认事项有责任人及计划确认时间。
材料不完整的,应明确补充内容及责任人后完善;涉及不确定性的,可先组织澄清或技术验证。
材料不完整的,应明确补充内容及责任人后完善;涉及不确定性的,可先组织澄清或技术验证。实施范围与功能说明、范围外事项由开发责任人在需求评审时提出,不作为业务方提交评审的前置必填项。
需求负责人和开发负责人共同组织评审,相关设计或协作人员按需参与。评审可采用会议或书面确认方式,结论应统一归档。
评审应明确:
1. 业务目标、实施范围及范围外事项。
1. 业务目标,以及由开发责任人提出、与业务方共同确认的实施范围与功能说明、范围外事项。
2. 验收标准、验收责任人及确认方式。
3. 设计稿、技术方案和接口约定的交付要求。
4. 依赖、风险及待确认事项的处理责任人。
5. 工作量、提测时间、验收反馈截止时间及计划上线时间。
需求负责人负责业务取舍,开发负责人负责技术可行性和工作量评估。范围、资源与时间无法同时满足时,应协调调整范围、资源或计划,并形成确认记录。
开发责任人负责提出并完善方案,需求负责人代表业务方确认业务取舍、范围与预期结果。方案应记录版本、双方确认人及确认时间;功能清单与详细说明应一致。开发负责人同时负责技术可行性和工作量评估。范围、资源与时间无法同时满足时,应协调调整范围、资源或计划,并形成确认记录。
核心范围及验收标准未明确,或未决事项可能改变核心方案、主要工作量的,不应进入正式开发排期,可先安排调研或技术验证。
@@ -12,9 +12,7 @@
期望上线时间及业务依据:
【提交评审前补充】
实施范围:
范围外事项:
功能说明及验收标准/文档链接:
业务验收标准/文档链接:
建议优先级及依据:
数据来自哪里、由谁提供/说明链接(如适用):
依赖与风险:
@@ -22,11 +20,19 @@
需求文档版本/修订日期:
参考材料及链接:
【评审及排期时确认】
【需求评审时由开发责任人提出方案,与业务方确认】
开发责任人:系统管理员(默认,无需填写)
实施范围与功能说明:
范围外事项(无则填“无”):
方案版本/链接:
业务方确认人:
双方确认结论及时间:
【排期时确认】
评审结论及确认人:
确认优先级:
设计负责人(如适用):
开发负责人:
开发负责人:系统管理员(默认,无需填写)
预计工作量:
计划提测时间:
验收反馈截止时间:
@@ -23,7 +23,7 @@
使用入口及触发场景:
前置条件:
四、范围与功能清单
四、范围与功能清单(需求评审时由开发责任人提出,与业务方确认)
实施范围:
范围外事项:
功能清单(编号、名称、预期结果):
@@ -33,7 +33,7 @@
判断条件、状态流转及角色交接(如适用):
关联流程图/原型及版本:
六、功能详细说明(每项功能分别填写)
六、功能详细说明(需求评审时由开发责任人逐项提出,与业务方确认)
功能编号及名称:
角色、入口及前置条件:
需要填写或选择的内容、必填项及默认值:
@@ -72,6 +72,8 @@
十一、版本与确认记录
版本、日期及变更说明:
评审结论、确认人及时间:
方案版本/链接:
开发责任人、业务方确认人:
评审结论及双方确认时间:
关联变更记录:
```
+50
View File
@@ -0,0 +1,50 @@
[
{
"source": "开发SOP_公示版.md",
"sourceSha256": "1e50c3b033d2eb5bba68c919ede2ea2fd32c7ba1f6b12bf21838795ee1bb87c0",
"file": "开发SOP_公示版.docx",
"fileSha256": "9791b16c14483d0862d5d1d3fcdb00e98270fb0133f64d87a36cc5cd5a2c0467"
},
{
"source": "附件01_需求登记模板.md",
"sourceSha256": "33dc4faed6fdb898639d2f005897ceaa548e8dd714e47cb901353818b3e45bcb",
"file": "附件01_需求登记模板.docx",
"fileSha256": "c7a6438f9a11b1ecc4b007932172e194611fe5e946d64e81ccfba071690612de"
},
{
"source": "附件02_需求文档模板.md",
"sourceSha256": "f281c5fae2e6fa305ce65f21b655e3cbccea06f3804780423d1e09273a9e7d2c",
"file": "附件02_需求文档模板.docx",
"fileSha256": "2ec08704e97aefda1c0e23900817ba9760de48263658dbeccc1876738ba24954"
},
{
"source": "附件03_数据来源填写模板.md",
"sourceSha256": "9df432ac80a992ab40ee22df5b6f393a64c4dd4478fbb5e3bddd0324fb40f6dd",
"file": "附件03_数据来源填写模板.docx",
"fileSha256": "9491d2fd5ecea18e116c83f74b5406d5c08fbb352c12574966b1d6a07d2e3367"
},
{
"source": "附件04_验收记录模板.md",
"sourceSha256": "8668fa1ed3b26e6bdd6448f4aa62b66f32c7fc08d787e851f5c2ad0dd9bb22c7",
"file": "附件04_验收记录模板.docx",
"fileSha256": "d7c8f114e326147802f37014670b271e9387b52c9c8df874eb5865c0743dd73d"
},
{
"source": "附件05_需求变更记录模板.md",
"sourceSha256": "901fc3201dc13050c12d4a8396d876370ec710f0df124abb8744861c77a3afde",
"file": "附件05_需求变更记录模板.docx",
"fileSha256": "23a60c7659617cfef265847618b06a5f72f66de82e33bb1a03e9e723cfadd8ae"
},
{
"source": "附件06_缺陷记录模板.md",
"sourceSha256": "a13f2bfbcab9524896da8cfa2c371a44a1a081b619e55a940e08a4f873b91a47",
"file": "附件06_缺陷记录模板.docx",
"fileSha256": "46c7c7ac2fcffcfe6e677d4e22091867bccd1de21932bfa548aa4ebe5240f2f1"
},
{
"source": "附件07_发布记录模板.md",
"sourceSha256": "c3dc55d2c4623dc3aee5982aa4f1de207b406a19c6dd64b92cbd8be0b4f5fb44",
"file": "附件07_发布记录模板.docx",
"fileSha256": "f2648d854dba338f035a37b3a66ce6698e609336115837875ef60f7d4c521ee5"
}
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-13
View File
@@ -1,13 +0,0 @@
import { env } from "cloudflare:workers";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./schema";
export function getDb() {
if (!env.DB) {
throw new Error(
"Cloudflare D1 binding `DB` is unavailable. Set the `d1` field in .openai/hosting.json to `DB` or let your control plane inject the real binding values before using the database."
);
}
return drizzle(env.DB, { schema });
}
-5
View File
@@ -1,5 +0,0 @@
import { sqliteTable, text, integer, index } from 'drizzle-orm/sqlite-core';
export const demands = sqliteTable('demands', {
id: text('id').primaryKey(), ownerId: text('owner_id').notNull(), payload: text('payload').notNull(),
revision: integer('revision').notNull().default(1), updatedAt: text('updated_at').notNull(),
}, table => [index('idx_demands_owner_updated').on(table.ownerId, table.updatedAt)]);
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
out: "./drizzle",
schema: "./db/schema.ts",
dialect: "sqlite",
});
-9
View File
@@ -1,9 +0,0 @@
CREATE TABLE `demands` (
`id` text PRIMARY KEY NOT NULL,
`owner_id` text NOT NULL,
`payload` text NOT NULL,
`revision` integer DEFAULT 1 NOT NULL,
`updated_at` text NOT NULL
);
--> statement-breakpoint
CREATE INDEX `idx_demands_owner_updated` ON `demands` (`owner_id`,`updated_at`);
-73
View File
@@ -1,73 +0,0 @@
{
"version": "6",
"dialect": "sqlite",
"id": "6c126420-5640-4245-a5c2-da4fbece0048",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"demands": {
"name": "demands",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"owner_id": {
"name": "owner_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"payload": {
"name": "payload",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"revision": {
"name": "revision",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 1
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"idx_demands_owner_updated": {
"name": "idx_demands_owner_updated",
"columns": [
"owner_id",
"updated_at"
],
"isUnique": false
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
-13
View File
@@ -1,13 +0,0 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1789539896010,
"tag": "0000_curvy_paibok",
"breakpoints": true
}
]
}
-58
View File
@@ -1,58 +0,0 @@
import { desc } from "drizzle-orm";
import { getDb } from "../../../../../db";
import { notes } from "../../../db/schema";
function toRouteErrorMessage(error: unknown) {
const message = error instanceof Error ? error.message : "Unexpected error";
const detail =
error instanceof Error && error.cause instanceof Error ? error.cause.message : "";
const combined = `${message}\n${detail}`;
if (combined.includes("no such table") || combined.includes('from "notes"')) {
return "The notes table is unavailable. Generate the migration locally with `npm run db:generate`, then deploy so the platform can apply the generated SQL to the real D1 database.";
}
return message;
}
export async function GET() {
try {
const db = getDb();
const rows = await db
.select()
.from(notes)
.orderBy(desc(notes.createdAt), desc(notes.id))
.limit(20);
return Response.json({ notes: rows });
} catch (error) {
return Response.json(
{ error: toRouteErrorMessage(error) },
{ status: 500 }
);
}
}
export async function POST(request: Request) {
try {
const payload = (await request.json()) as {
title?: string;
content?: string;
};
const title = payload.title?.trim() ?? "";
const content = payload.content?.trim() ?? "";
if (!title) {
return Response.json({ error: "title is required" }, { status: 400 });
}
const db = getDb();
const [note] = await db.insert(notes).values({ title, content }).returning();
return Response.json({ note }, { status: 201 });
} catch (error) {
return Response.json(
{ error: toRouteErrorMessage(error) },
{ status: 500 }
);
}
}
-9
View File
@@ -1,9 +0,0 @@
import { sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const notes = sqliteTable("notes", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title").notNull(),
content: text("content").notNull().default(""),
createdAt: text("created_at").notNull().default(sql`CURRENT_TIMESTAMP`),
});
+6
View File
@@ -0,0 +1,6 @@
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs' && process.env.NEXT_PHASE !== 'phase-production-build') {
const { startFeishuNotificationWorker } = await import('./lib/server/feishu-notifications');
startFeishuNotificationWorker();
}
}
+9
View File
@@ -0,0 +1,9 @@
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
export const MAX_ATTACHMENTS = 10;
export const STAGED_ATTACHMENT_TTL_MS = 24 * 60 * 60 * 1000;
export type Attachment = { id: string; name: string; size: number; createdAt: string };
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
+7
View File
@@ -0,0 +1,7 @@
/** Only app-relative navigation is accepted, including after an OAuth round trip. */
export function safeReturnTo(value: unknown): string {
if (typeof value !== 'string' || value.length > 2048 || !value.startsWith('/') || value.startsWith('//') || /[\\\u0000-\u0020\u007f]/.test(value)) return '/';
const url = new URL(value, 'https://local.invalid');
if (url.origin !== 'https://local.invalid' || url.pathname.startsWith('//') || url.pathname.startsWith('/api/') || url.pathname === '/login') return '/';
return url.pathname + url.search + url.hash;
}
+9
View File
@@ -0,0 +1,9 @@
/** Build-time public prefix. Keep in sync with Next.js `basePath`. */
export const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
/** Prefix browser-native app URLs; Next.js Link/router/redirect already do this. */
export function appPath(path: string): string {
if (!basePath || !path.startsWith('/') || path.startsWith('//') || path.startsWith('/\\')) return path;
if (path === basePath || path.startsWith(`${basePath}/`) || path.startsWith(`${basePath}?`) || path.startsWith(`${basePath}#`)) return path;
return `${basePath}${path}`;
}
+36
View File
@@ -0,0 +1,36 @@
import type { Attachment } from './attachments.ts';
import type { Demand, Fields } from './demand.ts';
export type ReviewPerson = { userId: string; username: string; displayName: string };
export type ReviewProposal = {
version: number;
scope: string;
outOfScope: string;
developer: ReviewPerson;
submittedAt: string;
businessFields: Fields;
businessAttachments?: Attachment[];
invalidated?: { time: string; reason: string };
decision?: { result: 'confirmed' | 'changes_requested'; actor: ReviewPerson; time: string; comment: string };
};
export type DemandReview = { developer: ReviewPerson; proposals: ReviewProposal[] };
export type DemandAccess = { business: boolean; developer: boolean; canTakeOverDevelopment?: boolean };
export function currentProposal(d: Demand): ReviewProposal | undefined {
return d.review?.proposals.at(-1);
}
export function reviewStage(d: Demand): string {
if (!d.reviewReady) return '资料待补充';
if (!d.review) return '待开发提出方案';
const proposal = currentProposal(d);
if (!proposal || proposal.invalidated) return '待开发提出方案';
if (proposal.decision?.result === 'confirmed') return '方案已确认';
if (proposal.decision?.result === 'changes_requested') return '待开发修改方案';
return '待业务确认方案';
}
export function invalidateProposal(d: Demand, time: string, reason: string): void {
const proposal = currentProposal(d);
if (proposal && !proposal.invalidated) proposal.invalidated = { time, reason };
}
+18
View File
@@ -0,0 +1,18 @@
import type { Demand } from './demand';
export type SavedDemandWrite = { version: number; demand: Demand };
/** Retain writes acknowledged after a GET began without dropping its other records. */
export function mergeDemandSnapshot(
snapshot: Demand[],
writes: Iterable<SavedDemandWrite>,
startedAtVersion: number,
): Demand[] {
const records = new Map(snapshot.map(demand => [demand.id, demand]));
for (const { version, demand } of writes) {
if (version <= startedAtVersion) continue;
const serverRecord = records.get(demand.id);
if (!serverRecord || serverRecord.revision <= demand.revision) records.set(demand.id, demand);
}
return [...records.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
}
+15 -3
View File
@@ -1,4 +1,7 @@
import { z } from 'zod';
import type { Attachment } from './attachments.ts';
import { workflowTask, pendingChange, type ChangeRecord, type Delivery, type DeliveryPlan, type TestingRound } from './workflow.ts';
import { reviewStage, type DemandAccess, type DemandReview } from './demand-review.ts';
export const statuses = ['待评审','已排期','开发中','待验收','待发布','已上线','已完成'] as const;
export const fieldSchema = z.object({
title:z.string().trim().max(100),project:z.string().trim().max(100),module:z.string().trim().max(100),type:z.enum(['新增功能','功能优化','缺陷修复','配置/数据变更']),proposer:z.string().trim().max(100),department:z.string().trim().max(100),source:z.string().trim().max(200),owner:z.string().trim().max(100),
@@ -8,14 +11,23 @@ export const fieldSchema = z.object({
export type Fields=z.infer<typeof fieldSchema>;
export type History={time:string;actor:string;action:string;detail:string};
export type AcceptanceItem={id:string;feature:string;scenario:string;expected:string};
export type Demand={id:string;revision:number;fields:Fields;status:string;createdAt:string;updatedAt:string;reviewReady:boolean;blocked?:string;history:History[];changes:{time:string;content:string;reason:string;actor:string;status:string;originalVersion:string;originalFields?:Fields}[];acceptance?:{testVersion:string;environment:string;deadline:string;items:AcceptanceItem[];instructions:string};acceptanceRecords?:{time:string;actor:string;version:string;testVersion:string;results:string[];notes:string;passed:boolean;items?: (AcceptanceItem & {result:string})[];environment?:string}[];plan?:{developer:string;testDate:string;releaseDate:string};demo?:boolean};
export type Demand={attachments?:Attachment[];review?:DemandReview;access?:DemandAccess;id:string;revision:number;fields:Fields;status:string;createdAt:string;updatedAt:string;reviewReady:boolean;blocked?:string;history:History[];changes:ChangeRecord[];acceptance?:TestingRound;acceptanceRecords?:{time:string;actor:string;version:string;testVersion:string;round?:number;results:string[];notes:string;passed:boolean;items?: (AcceptanceItem & {result:string})[];environment?:string}[];plan?:DeliveryPlan;delivery?:Delivery};
export const emptyFields:Fields={title:'',project:'',module:'',type:'新增功能',proposer:'',department:'',source:'',owner:'',background:'',impact:'',goal:'',expectedDate:'',noFixedDate:false,dateReason:'',scope:'',outOfScope:'',criteria:'',priority:'P2',priorityReason:'',dataSource:'',dataContact:'',noData:false,risk:'',pending:'',references:'',version:'v1.0'};
export function missingFields(f:Fields,review=false):string[]{
const required: [keyof Fields,string][]=[['title','需求标题'],['project','所属项目'],['module','业务模块'],['proposer','提出人'],['department','所属部门'],['source','需求来源'],['owner','需求负责人'],['background','业务背景'],['impact','影响对象与依据'],['goal','预期目标']];
const missing=required.filter(([k])=>!f[k]).map(([,label])=>label);
if(!f.noFixedDate){if(!/^\d{4}-\d{2}-\d{2}$/.test(f.expectedDate)||Number.isNaN(Date.parse(f.expectedDate))||new Date(f.expectedDate).toISOString().slice(0,10)!==f.expectedDate)missing.push('有效的期望上线日期');if(!f.dateReason)missing.push('期望日期依据');}
if(review){const rs:[keyof Fields,string][]=[['scope','实施范围与功能说明'],['outOfScope','范围外事项'],['criteria','验收标准'],['priorityReason','优先级依据'],['risk','依赖与风险'],['pending','待确认事项'],['version','文档版本']];missing.push(...rs.filter(([k])=>!f[k]).map(([,l])=>l));if(!f.noData){if(!f.dataSource)missing.push('数据来源');if(!f.dataContact)missing.push('数据提供人');}}
if(review){const rs:[keyof Fields,string][]=[['criteria','验收标准'],['priorityReason','优先级依据'],['risk','依赖与风险'],['pending','待确认事项'],['version','文档版本']];missing.push(...rs.filter(([k])=>!f[k]).map(([,l])=>l));if(!f.noData){if(!f.dataSource)missing.push('数据来源');if(!f.dataContact)missing.push('数据提供人');}}
return missing;
}
export function needsAction(d:Demand){return d.status==='待验收'||(d.status==='待评审'&&!d.reviewReady);}
export function needsAction(d:Demand){
if(pendingChange(d)||d.blocked)return Boolean(workflowTask(d));
if(workflowTask(d))return true;
const business=d.access?.business??true;
if(d.status==='待验收')return business;
if(d.status!=='待评审')return false;
const stage=reviewStage(d);
return Boolean(business&&['资料待补充','待业务确认方案'].includes(stage)||d.access?.developer&&['待开发提出方案','待开发修改方案'].includes(stage));
}
export function isActive(d:Demand){return !['草稿','已完成','已取消'].includes(d.status);}
export function isMyDemand(d:Demand){return d.access===undefined||d.access.business||d.access.developer;}
-11
View File
@@ -1,11 +0,0 @@
import { emptyFields, type Demand } from './demand';
const entries=[
['销售订单批量导出','待验收','P1','2026-09-20','销售部'],['客户信息统一管理','开发中','P1','2026-09-25','客户服务部'],['经营数据看板','待评审','P2','2026-09-30','运营部'],['采购审批流程优化','待评审','P2','2026-10-08','采购部'],['库存预警自动通知','已完成','P2','2026-09-12','仓储部'],['合同到期自动提醒','已排期','P2','2026-10-12','销售部'],['门店经营周报','开发中','P1','2026-09-28','运营部'],['供应商资料归档','已排期','P2','2026-10-15','采购部'],['员工报销查询','草稿','P2','','财务部'],['客户回访记录','草稿','P2','','客户服务部'],
];
export const demoDemands:Demand[]=entries.map(([title,status,priority,date,department],i)=>({
id:`REQ-202609${String(14-i).padStart(2,'0')}-${String(8-i>0?8-i:12-i).padStart(3,'0')}`,revision:1,demo:true,status,reviewReady:status!=='待评审',createdAt:`2026-09-${String(14-i).padStart(2,'0')}T02:00:00.000Z`,updatedAt:'2026-09-16T02:00:00.000Z',
fields:{...emptyFields,title,project:'企业业务平台',module:title.slice(0,4),type:'功能优化',proposer:'业务用户',department,source:'业务日常反馈',owner:'业务用户',background:i===0?'销售同事每周手动整理订单数据,需要逐页复制订单信息,耗时较长且容易遗漏。':'当前相关业务信息分散,需要多次查询和人工处理,影响日常工作效率。',impact:department+'业务同事;以日常操作记录和部门反馈为依据。',goal:i===0?'支持一次导出筛选后的订单,确保导出内容与列表结果一致,减少重复整理。':'统一业务信息和操作入口,减少重复工作,保证关键业务结果准确。',expectedDate:date,noFixedDate:!date,dateReason:'配合部门月度业务计划',scope:'F-01:支持按业务条件筛选记录。\nF-02:支持导出当前筛选结果。',outOfScope:'本次不包含历史数据清洗。',criteria:'AC-01:使用有效条件筛选时,仅展示符合条件的记录。\nAC-02:导出文件应包含筛选结果,字段与列表一致。\nAC-03:无记录时提示暂无数据,不生成空文件。',priority:priority as 'P1'|'P2',priorityReason:'支持近期业务目标,按部门计划推进。',dataSource:i===2?'':'企业业务平台中的业务管理列表',dataContact:i===2?'':'各部门业务负责人',risk:'无',pending:i===2?'待确认:指标数据来源;责任人:业务用户;计划确认时间:2026-09-18。':'无'},
history:[{time:'2026-09-10T02:00:00Z',actor:'业务用户',action:'登记需求',detail:'已登记业务背景、目标与影响范围。'},...(status==='待验收'?[{time:'2026-09-15T08:30:00Z',actor:'开发负责人(示例)',action:'提交业务验收',detail:'审查、自测及集成验证通过;已提供测试版本与验收清单。'}]:[])],changes:[],
...(['已排期','开发中','待验收'].includes(status)?{plan:{developer:'开发负责人(示例)',testDate:'2026-09-18',releaseDate:date}}:{}),
...(status==='待验收'?{acceptance:{testVersion:'v1.2.0-rc.1(示例)',environment:'示例环境,仅用于体验验收流程',deadline:'2026-09-19',instructions:'使用测试账号筛选订单后导出,核对导出内容与筛选结果。账号及数据通过约定受限渠道获取。',items:[{id:'AC-01',feature:'F-01 条件筛选',scenario:'选择订单状态为已完成',expected:'仅展示已完成的订单。'},{id:'AC-02',feature:'F-02 批量导出',scenario:'导出当前筛选结果',expected:'文件中的订单、金额和数量与列表一致。'},{id:'AC-03',feature:'F-02 空数据处理',scenario:'筛选没有匹配记录的条件并导出',expected:'提示暂无数据,不生成空文件。'}]}}:{}),
}));
+20
View File
@@ -0,0 +1,20 @@
import { appPath } from './base-path.ts';
export const FEISHU_TEMPLATE_DIRECTORY = 'https://ecnldnvsv8es.feishu.cn/wiki/Bvnbw852biK7qRkhwJkcOIvun4f?from=from_copylink';
export const documents = [
{ id: 'sop', title: '软件开发流程管理规范', filename: '开发SOP_公示版.md', description: '职责、需求评审、验收与发布的完整约定。' },
{ id: 'registration', title: '需求登记模板', filename: '附件01_需求登记模板.md', description: '用于登记业务问题、目标、负责人及期望时间。' },
{ id: 'requirement', title: '需求说明模板', filename: '附件02_需求文档模板.md', description: '用于补充业务背景、目标、场景及验收标准;方案部分由开发责任人在评审时填写。' },
{ id: 'data-source', title: '数据来源模板', filename: '附件03_数据来源填写模板.md', description: '用于说明数据从哪里来、由谁提供、更新频率及参考样例。' },
{ id: 'acceptance', title: '验收记录模板', filename: '附件04_验收记录模板.md', description: '业务验收时记录逐项结果、证据及确认结论。' },
{ id: 'change', title: '需求变更记录模板', filename: '附件05_需求变更记录模板.md', description: '记录变更原因、影响、调整后的计划和确认人。' },
{ id: 'defect', title: '缺陷记录模板', filename: '附件06_缺陷记录模板.md', description: '记录复现步骤、预期与实际结果、修复和复验情况。' },
{ id: 'release', title: '发布记录模板', filename: '附件07_发布记录模板.md', description: '记录上线版本、检查结果、恢复方式和生产验证。' },
] as const;
export type DocumentId = typeof documents[number]['id'];
export type DocumentInfo = typeof documents[number];
export function findDocument(value: string): DocumentInfo | undefined { return documents.find(item => item.id === value || item.filename === value); }
export function templateDownloadUrl(id: DocumentId): string { return appPath('/api/documents/' + encodeURIComponent(findDocument(id)!.filename) + '?format=docx'); }
export function linkedDocument(href: string): DocumentInfo | undefined {
try { return findDocument(decodeURIComponent(href.split('#')[0].split('?')[0].split('/').at(-1) || '')); } catch { return undefined; }
}
+27
View File
@@ -0,0 +1,27 @@
export const feishuErrors: Record<string, string> = {
unavailable: '飞书登录暂未配置完成,请使用账号密码登录或联系管理员。',
expired: '飞书授权已过期或浏览器状态不匹配,请重新发起授权。',
denied: '已取消飞书授权,你可以重试或使用账号密码登录。',
unbound: '此飞书身份尚未关联账号,请重新使用飞书登录,系统会自动注册普通成员账号。',
conflict: '此飞书身份或系统账号已有绑定,请先解除原有绑定。',
tenant: '此飞书账号不属于允许登录的企业,请联系管理员。',
session: '系统登录状态已变化,请重新登录后绑定飞书。',
rate_limited: '登录尝试过于频繁,请稍后再试。',
source: '登录请求来源无效,请从系统访问地址重新打开;如持续出现,请联系管理员检查代理配置。',
failed: '飞书授权暂未完成,请重试;如持续失败,请联系管理员检查应用配置。',
};
export function feishuErrorMessage(code: unknown): string {
return typeof code === 'string' && Object.hasOwn(feishuErrors, code) ? feishuErrors[code] : '';
}
export type FeishuBinding = { name: string; boundAt: string } | null;
export type FeishuDelivery = {
id: string; demandId: string; revision: number; status: 'pending' | 'sending' | 'sent' | 'failed';
attempts: number; lastError: string | null; createdAt: string; sentAt: string | null;
};
export type FeishuDeliveryFilter = 'all' | 'failed';
export type FeishuStatus = {
loginConfigured: boolean; callbackUrl: string; tenantRestricted: boolean;
botConfigured: boolean; botSigned: boolean; configurationError: string | null;
deliveries: FeishuDelivery[];
deliveryFilter: FeishuDeliveryFilter; nextCursor: string | null; failedCount: number;
};
+99
View File
@@ -0,0 +1,99 @@
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, STAGED_ATTACHMENT_TTL_MS, type Attachment } from '../attachments.ts';
import type { Demand } from '../demand.ts';
import { invalidateProposal } from '../demand-review.ts';
import { AuthError, jsonResponse } from './auth.ts';
import { getDatabase } from './database.ts';
import { readableDemandWhere, readableDemandBindings, type DemandViewer } from './demand-access.ts';
type AttachmentRow = { id: string; owner_id: string; demand_id: string | null; name: string; size: number; created_at: string };
const metadata = (row: AttachmentRow): Attachment => ({ id: row.id, name: row.name, size: row.size, createdAt: row.created_at });
const idSchema = z.string().uuid();
export function attachmentIds(value: unknown): string[] | undefined {
if (value === undefined) return undefined;
const parsed = z.array(idSchema).max(MAX_ATTACHMENTS).safeParse(value);
if (!parsed.success || new Set(parsed.data).size !== parsed.data.length) throw new AuthError(`附件列表无效,每条需求最多 ${MAX_ATTACHMENTS} 个附件。`);
return parsed.data;
}
export function storeUpload(userId: string, inputName: string, bytes: Uint8Array): Attachment {
const name = inputName.replace(/[\\/\u0000-\u001f\u007f]/g, '_').trim();
if (!name || name.length > 200) throw new AuthError('文件名须为 1–200 个字符。');
if (!bytes.byteLength) throw new AuthError('不能上传空文件。');
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413);
const database = getDatabase();
return database.transaction(() => {
const now = new Date().toISOString();
database.prepare('DELETE FROM attachments WHERE demand_id IS NULL AND created_at < ?').bind(new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).run();
const pending = database.prepare('SELECT COUNT(*) AS count FROM attachments WHERE owner_id = ? AND demand_id IS NULL').bind(userId).first<{ count: number }>()!;
if (pending.count >= MAX_ATTACHMENTS) throw new AuthError('未保存附件已达 10 个,请先保存需求或移除未使用的附件。', 409);
const id = randomUUID();
database.prepare('INSERT INTO attachments (id, owner_id, name, size, content, created_at) VALUES (?, ?, ?, ?, ?, ?)').bind(id, userId, name, bytes.byteLength, bytes, now).run();
return { id, name, size: bytes.byteLength, createdAt: now };
});
}
/** Called inside the same transaction that writes the demand. No claims or removals escape a failed save. */
export function syncDemandAttachments(record: Demand, ownerId: string, ids: string[] | undefined, now: string): boolean {
if (ids === undefined) return false;
const database = getDatabase();
const cutoff = new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString();
const selected = ids.map(id => {
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
if (!row || row.owner_id !== ownerId || (row.demand_id !== null && row.demand_id !== record.id) || (!row.demand_id && row.created_at < cutoff)) throw new AuthError('附件已失效或无法访问,请移除后重新上传。');
return metadata(row);
});
const before = (record.attachments ?? []).map(file => file.id).sort().join(',');
const changed = before !== [...ids].sort().join(',');
if (changed) invalidateProposal(record, now, '参考附件已修改,需开发责任人重新提交方案并由业务方确认。');
record.attachments = selected;
return changed;
}
/** The demand row must exist first so foreign keys remain valid. Historical review files are retained. */
export function commitDemandAttachments(record: Demand, ownerId: string): void {
const database = getDatabase();
for (const file of record.attachments ?? []) database.prepare('UPDATE attachments SET demand_id = ? WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(record.id, file.id, ownerId).run();
const retained = new Set([
...(record.attachments ?? []).map(file => file.id),
...(record.review?.proposals ?? []).flatMap(proposal => (proposal.businessAttachments ?? []).map(file => file.id)),
]);
for (const row of database.prepare('SELECT id FROM attachments WHERE demand_id = ?').bind(record.id).all<{ id: string }>().results) {
if (!retained.has(row.id)) database.prepare('DELETE FROM attachments WHERE id = ? AND demand_id = ?').bind(row.id, record.id).run();
}
}
export function downloadAttachment(id: string, user: DemandViewer): { file: Attachment; bytes: Uint8Array } {
if (!idSchema.safeParse(id).success) throw new AuthError('找不到该附件或你没有访问权限。', 404);
const database = getDatabase();
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
if (!row) throw new AuthError('找不到该附件或你没有访问权限。', 404);
if (row.demand_id) {
const demand = database.prepare(`SELECT id FROM demands WHERE id = ? AND ${readableDemandWhere}`)
.bind(row.demand_id, ...readableDemandBindings(user)).first();
if (!demand) throw new AuthError('找不到该附件或你没有访问权限。', 404);
} else if (row.owner_id !== user.userId || row.created_at < new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()) {
throw new AuthError('找不到该附件或你没有访问权限。', 404);
}
const content = database.prepare('SELECT content FROM attachments WHERE id = ?').bind(id).first<{ content: Uint8Array }>()!;
return { file: metadata(row), bytes: content.content };
}
export function deleteStagedAttachment(id: string, userId: string): void {
const database = getDatabase();
const result = database.prepare('DELETE FROM attachments WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(id, userId).run();
if (!result.meta.changes) throw new AuthError('该附件已保存或无法访问,请在需求表单中移除并保存。', 409);
}
export function listStagedAttachments(userId: string): Attachment[] {
return getDatabase().prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE owner_id = ? AND demand_id IS NULL AND created_at >= ? ORDER BY created_at')
.bind(userId, new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).all<AttachmentRow>().results.map(metadata);
}
export function attachmentFailure(error: unknown): Response {
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
console.error('Attachment operation failed', error);
return jsonResponse({ error: '附件服务暂时不可用,请稍后重试。' }, 503);
}
+295
View File
@@ -0,0 +1,295 @@
import { createHash, randomBytes } from 'node:crypto';
import { isIP } from 'node:net';
import { basePath } from '../base-path.ts';
import { applicationOrigin, getDatabase, normalizeDisplayName, normalizeUsername, type AccountRow } from './database.ts';
import { hashPassword, hashPasswordSync, hasStoredPassword, validatePassword, verifyPassword } from './password.ts';
export type AuthUser = {
userId: string; username: string; displayName: string;
role: 'admin' | 'user'; mustChangePassword: boolean;
};
export type AdminUser = AuthUser & { disabled: boolean; createdAt: string; lastLoginAt: string | null };
export class AuthError extends Error {
status: number;
constructor(message: string, status = 400) { super(message); this.name = 'AuthError'; this.status = status; }
}
const SESSION_SECONDS = 7 * 24 * 60 * 60;
const COOKIE_NAME = 'demand_session';
let dummyPasswordHash: string | undefined;
function publicUser(account: AccountRow): AuthUser {
return { userId: account.id, username: account.username, displayName: account.display_name, role: account.role, mustChangePassword: Boolean(account.must_change_password) };
}
function accountById(id: string): AccountRow | null {
return getDatabase().prepare('SELECT * FROM accounts WHERE id = ?').bind(id).first<AccountRow>();
}
export function hasAccountPassword(userId: string): boolean {
return hasStoredPassword(accountById(userId)?.password_hash);
}
function tokenHash(token: string): string { return createHash('sha256').update(token).digest('hex'); }
export function isSameOrigin(request: Request): boolean {
const origin = request.headers.get('origin');
if (!origin || origin === 'null') return false;
const fetchSite = request.headers.get('sec-fetch-site');
if (fetchSite && !['same-origin', 'none'].includes(fetchSite)) return false;
return origin === applicationOrigin(request);
}
export function assertSameOrigin(request: Request): void {
if (!isSameOrigin(request)) throw new AuthError('请求来源无效,请从系统访问地址重新打开页面。', 403);
}
export function sessionCookie(token: string, request?: Request): string {
const secure = applicationOrigin(request).startsWith('https://') ? '; Secure' : '';
return `${COOKIE_NAME}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? SESSION_SECONDS : 0}${secure}`;
}
function issueSession(account: AccountRow): { user: AuthUser; token: string } {
const database = getDatabase();
const token = randomBytes(32).toString('base64url');
const now = Date.now();
database.prepare('DELETE FROM sessions WHERE expires_at <= ?').bind(now).run();
database.prepare('INSERT INTO sessions (token_hash, account_id, expires_at, created_at) VALUES (?, ?, ?, ?)')
.bind(tokenHash(token), account.id, now + SESSION_SECONDS * 1000, now).run();
return { user: publicUser(account), token };
}
/** Called only after a server-side identity provider has authenticated a bound account. */
export function issueIdentitySession(accountId: string): { user: AuthUser; token: string } {
const account = accountById(accountId);
if (!account || account.disabled) throw new AuthError('账号已停用,请联系管理员。', 403);
getDatabase().prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?')
.bind(new Date().toISOString(), account.id).run();
return issueSession(account);
}
export function authenticateSession(token: string | undefined): AuthUser | null {
if (!token || !/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
const account = getDatabase().prepare(`SELECT accounts.* FROM sessions JOIN accounts ON accounts.id = sessions.account_id
WHERE sessions.token_hash = ? AND sessions.expires_at > ? AND accounts.disabled = 0`)
.bind(tokenHash(token), Date.now()).first<AccountRow>();
return account ? publicUser(account) : null;
}
export async function getCurrentUser(): Promise<AuthUser | null> {
const { cookies } = await import('next/headers');
return authenticateSession((await cookies()).get(COOKIE_NAME)?.value);
}
export async function requireUser(returnTo = '/'): Promise<AuthUser> {
const { redirect } = await import('next/navigation');
const user = await getCurrentUser();
const safeReturn = returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/';
if (!user) return redirect(`/login?next=${encodeURIComponent(safeReturn)}`);
if (user.mustChangePassword && safeReturn.split('?')[0] !== '/account/password') redirect('/account/password');
return user;
}
export async function requireApiUser(options: { admin?: boolean; allowPasswordChange?: boolean } = {}): Promise<AuthUser> {
const user = await getCurrentUser();
if (!user) throw new AuthError('请先登录。', 401);
if (!options.allowPasswordChange && user.mustChangePassword) throw new AuthError('请先修改初始密码后继续。', 403);
if (options.admin && user.role !== 'admin') throw new AuthError('仅管理员可以管理账号。', 403);
return user;
}
function loginSourceKey(request?: Request): string | undefined {
const configuredHeader = process.env.LOGIN_CLIENT_IP_HEADER?.trim().toLowerCase();
if (!configuredHeader) return undefined;
if (!/^[a-z][a-z0-9-]{0,63}$/.test(configuredHeader)) throw new AuthError('登录来源配置无效,请联系管理员。', 503);
// Opt-in trust boundary: the reverse proxy must overwrite this single-IP header,
// and the application port must not be directly reachable by untrusted clients.
// Other forwarded headers are ignored; missing or invalid configured values fail closed.
const address = request?.headers.get(configuredHeader)?.trim();
const family = address && !address.includes('%') ? isIP(address) : 0;
if (!address || !family) throw new AuthError('登录来源信息无效,请联系管理员。', 403);
let normalized = address;
if (family === 6) {
normalized = new URL(`http://[${address}]/`).hostname.slice(1, -1);
// Equivalent IPv6 spellings and IPv4-mapped addresses share the same bucket.
const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(normalized);
if (mapped) {
const high = Number.parseInt(mapped[1], 16); const low = Number.parseInt(mapped[2], 16);
normalized = `${high >>> 8}.${high & 255}.${low >>> 8}.${low & 255}`;
}
}
return `source:${tokenHash(normalized)}`;
}
function consumeLoginAttempt(username: string | undefined, sourceKey?: string): void {
const database = getDatabase();
const now = Date.now();
// Database-backed limits survive restarts and work across local application processes.
// There is no shared global bucket: one source cannot spend another source's quota.
const buckets = [
...(sourceKey ? [{ key: sourceKey, span: 60_000, limit: 60 }] : []),
...(username !== undefined ? [{ key: `username:${tokenHash(username)}`, span: 15 * 60_000, limit: 5 }] : []),
];
if (!buckets.length) return;
database.transaction(() => {
database.prepare('DELETE FROM login_limits WHERE window_start < ?').bind(now - 15 * 60_000).run();
for (const bucket of buckets) {
const row = database.prepare('SELECT window_start, attempts FROM login_limits WHERE key = ?').bind(bucket.key).first<{ window_start: number; attempts: number }>();
if (row && now - row.window_start < bucket.span && row.attempts >= bucket.limit) {
throw new AuthError('登录尝试过于频繁,请稍后再试。', 429);
}
}
for (const bucket of buckets) {
database.prepare(`INSERT INTO login_limits (key, window_start, attempts) VALUES (?, ?, 1)
ON CONFLICT(key) DO UPDATE SET
attempts = CASE WHEN login_limits.window_start <= ? THEN 1 ELSE login_limits.attempts + 1 END,
window_start = CASE WHEN login_limits.window_start <= ? THEN excluded.window_start ELSE login_limits.window_start END`)
.bind(bucket.key, now, now - bucket.span, now - bucket.span).run();
}
});
}
/** OAuth and password login share the same trusted-source quota (when configured). */
export function consumeLoginSourceAttempt(request: Request): void {
consumeLoginAttempt(undefined, loginSourceKey(request));
}
export async function loginWithPassword(usernameInput: unknown, passwordInput: unknown, request?: Request): Promise<{ user: AuthUser; token: string }> {
if (typeof usernameInput !== 'string' || typeof passwordInput !== 'string' || !usernameInput.trim() || usernameInput.length > 128 || !passwordInput || passwordInput.length > 128) {
throw new AuthError('账号或密码错误。', 401);
}
const username = usernameInput.trim().toLowerCase();
consumeLoginAttempt(username, loginSourceKey(request));
const database = getDatabase();
const account = database.prepare('SELECT * FROM accounts WHERE username = ?').bind(username).first<AccountRow>();
dummyPasswordHash ??= hashPasswordSync('dummy timing password that never authenticates');
const valid = await verifyPassword(passwordInput, hasStoredPassword(account?.password_hash) ? account!.password_hash : dummyPasswordHash);
// Feishu-only accounts cannot authenticate using the timing dummy password.
if (!account || !hasStoredPassword(account.password_hash) || !valid || account.disabled) throw new AuthError('账号或密码错误。', 401);
return database.transaction(() => {
const current = accountById(account.id);
if (!current || current.disabled || current.password_hash !== account.password_hash) throw new AuthError('账号或密码错误。', 401);
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(username)}`).run();
database.prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?').bind(new Date().toISOString(), account.id).run();
return issueSession(current);
});
}
export function revokeSession(token: string | undefined): void {
if (token && /^[A-Za-z0-9_-]{43}$/.test(token)) getDatabase().prepare('DELETE FROM sessions WHERE token_hash = ?').bind(tokenHash(token)).run();
}
export async function logoutCurrentSession(): Promise<void> {
const { cookies } = await import('next/headers');
revokeSession((await cookies()).get(COOKIE_NAME)?.value);
}
export async function changeAccountPassword(userId: string, currentPassword: unknown, newPassword: unknown): Promise<{ user: AuthUser; token: string }> {
try { validatePassword(newPassword); } catch (error) { throw new AuthError((error as Error).message); }
const current = accountById(userId);
if (!current || current.disabled) throw new AuthError('账号已停用,请联系管理员。', 401);
if (hasStoredPassword(current.password_hash)) {
if (typeof currentPassword !== 'string' || currentPassword.length > 128 || !await verifyPassword(currentPassword, current.password_hash)) throw new AuthError('当前密码不正确。');
if (currentPassword === newPassword) throw new AuthError('新密码不能与当前密码相同。');
} else if (!getDatabase().prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(userId).first()) {
throw new AuthError('账号缺少可用的登录方式,请联系管理员。', 403);
}
const passwordHash = await hashPassword(newPassword);
return getDatabase().transaction(() => {
const fresh = accountById(userId);
if (!fresh || fresh.disabled || fresh.password_hash !== current.password_hash) throw new AuthError('账号状态已变化,请重新登录。', 409);
getDatabase().prepare('UPDATE accounts SET password_hash = ?, must_change_password = 0, updated_at = ? WHERE id = ?')
.bind(passwordHash, new Date().toISOString(), userId).run();
getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(userId).run();
return issueSession({ ...fresh, password_hash: passwordHash, must_change_password: 0 });
});
}
function activeAdmin(actorId: string): AccountRow {
const actor = accountById(actorId);
if (!actor || actor.disabled || actor.role !== 'admin' || actor.must_change_password) throw new AuthError('当前账号无权管理用户,请重新登录。', 403);
return actor;
}
export function listAccounts(actorId: string): AdminUser[] {
activeAdmin(actorId);
return getDatabase().prepare('SELECT * FROM accounts ORDER BY created_at ASC, username ASC').all<AccountRow>().results.map(account => ({
...publicUser(account), disabled: Boolean(account.disabled), createdAt: account.created_at, lastLoginAt: account.last_login_at,
}));
}
export async function createAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
activeAdmin(actorId);
let username: string; let displayName: string;
try { username = normalizeUsername(input.username); displayName = normalizeDisplayName(input.displayName); validatePassword(input.password); }
catch (error) { throw new AuthError((error as Error).message); }
if (!['admin', 'user'].includes(String(input.role))) throw new AuthError('账号角色无效。');
const passwordHash = await hashPassword(input.password as string);
return getDatabase().transaction(() => {
activeAdmin(actorId);
if (getDatabase().prepare('SELECT id FROM accounts WHERE username = ?').bind(username).first()) throw new AuthError('该账号已存在。', 409);
const now = new Date().toISOString();
const userId = randomBytes(16).toString('hex');
getDatabase().prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`).bind(userId, username, displayName, passwordHash, input.role as string, now, now).run();
return publicUser(accountById(userId)!);
});
}
export async function updateAccount(actorId: string, input: Record<string, unknown>): Promise<AuthUser> {
activeAdmin(actorId);
if (typeof input.id !== 'string' || input.id.length > 128 || !['disable', 'enable', 'reset-password'].includes(String(input.action))) throw new AuthError('账号操作无效。');
if (input.id === actorId && ['disable', 'reset-password'].includes(String(input.action))) throw new AuthError('不能停用或重置自己的账号;请使用“修改密码”。');
let passwordHash: string | undefined;
if (input.action === 'reset-password') {
try { validatePassword(input.password); } catch (error) { throw new AuthError((error as Error).message); }
passwordHash = await hashPassword(input.password as string);
}
return getDatabase().transaction(() => {
activeAdmin(actorId);
const target = accountById(input.id as string);
if (!target) throw new AuthError('找不到该账号。', 404);
const database = getDatabase();
const now = new Date().toISOString();
if (input.action === 'disable') {
const admins = database.prepare("SELECT COUNT(*) AS count FROM accounts WHERE role = 'admin' AND disabled = 0").first<{ count: number }>()!;
if (target.role === 'admin' && !target.disabled && admins.count <= 1) throw new AuthError('必须至少保留一位启用的管理员。', 409);
database.prepare('UPDATE accounts SET disabled = 1, updated_at = ? WHERE id = ?').bind(now, target.id).run();
} else if (input.action === 'enable') {
database.prepare('UPDATE accounts SET disabled = 0, updated_at = ? WHERE id = ?').bind(now, target.id).run();
} else {
database.prepare('UPDATE accounts SET password_hash = ?, must_change_password = 1, updated_at = ? WHERE id = ?').bind(passwordHash!, now, target.id).run();
database.prepare('DELETE FROM login_limits WHERE key = ?').bind(`username:${tokenHash(target.username)}`).run();
}
if (input.action !== 'enable') database.prepare('DELETE FROM sessions WHERE account_id = ?').bind(target.id).run();
return publicUser(accountById(target.id)!);
});
}
export function jsonResponse(value: unknown, status = 200, cookie?: string): Response {
const headers = new Headers({ 'Cache-Control': 'no-store' });
if (cookie) headers.set('Set-Cookie', cookie);
return Response.json(value, { status, headers });
}
export function authFailure(error: unknown): Response {
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
console.error('Account operation failed:', error instanceof Error ? error.message : 'Unknown failure');
return jsonResponse({ error: '账号服务暂时不可用,请联系管理员或稍后重试。' }, 503);
}
export async function readJsonObject(request: Request): Promise<Record<string, unknown>> {
if (!request.headers.get('content-type')?.toLowerCase().startsWith('application/json')) throw new AuthError('请使用 JSON 格式提交。', 415);
const reader = request.body?.getReader();
if (!reader) throw new AuthError('提交内容不能为空。');
const chunks: Uint8Array[] = []; let length = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
length += value.length;
if (length > 8192) { await reader.cancel(); throw new AuthError('提交内容过长。', 413); }
chunks.push(value);
}
try {
const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Invalid JSON object');
return parsed as Record<string, unknown>;
} catch { throw new AuthError('提交内容格式无效。'); }
}
+186
View File
@@ -0,0 +1,186 @@
import { mkdirSync, chmodSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
import { hashPasswordSync } from './password.ts';
export type AccountRole = 'admin' | 'user';
export type AccountRow = {
id: string; username: string; display_name: string; password_hash: string;
role: AccountRole; disabled: number; must_change_password: number;
created_at: string; updated_at: string; last_login_at: string | null;
};
export function normalizeUsername(value: unknown): string {
if (typeof value !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._@-]{2,63}$/.test(value.trim())) {
throw new Error('账号须为 3–64 位字母、数字或 . _ @ -,并以字母或数字开头。');
}
return value.trim().toLowerCase();
}
export function normalizeDisplayName(value: unknown): string {
if (typeof value !== 'string' || !value.trim() || value.trim().length > 80 || /[\u0000-\u001f\u007f]/.test(value)) {
throw new Error('姓名须为 1–80 个字符。');
}
return value.trim();
}
export function applicationOrigin(request?: Request): string {
const configured = process.env.APP_URL;
if (!configured) {
if (process.env.NODE_ENV === 'production') throw new Error('生产环境必须设置 APP_URL,例如 https://demand.example.com。');
return request ? new URL(request.url).origin : 'http://localhost:3000';
}
const url = new URL(configured);
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash) {
throw new Error('APP_URL 必须为系统的完整访问域名,例如 https://demand.example.com,不含路径。');
}
return url.origin;
}
class PreparedQuery {
private database: DatabaseSync;
private sql: string;
private values: SQLInputValue[];
constructor(database: DatabaseSync, sql: string, values: SQLInputValue[] = []) {
this.database = database; this.sql = sql; this.values = values;
}
bind(...values: SQLInputValue[]): PreparedQuery { return new PreparedQuery(this.database, this.sql, values); }
all<T = Record<string, unknown>>(): { results: T[] } {
return { results: this.database.prepare(this.sql).all(...this.values) as T[] };
}
first<T = Record<string, unknown>>(): T | null {
return (this.database.prepare(this.sql).get(...this.values) as T | undefined) ?? null;
}
run(): { meta: { changes: number; last_row_id: number | bigint } } {
const result = this.database.prepare(this.sql).run(...this.values);
return { meta: { changes: Number(result.changes), last_row_id: result.lastInsertRowid } };
}
}
export class AppDatabase {
private database: DatabaseSync;
constructor(database: DatabaseSync) { this.database = database; }
prepare(sql: string): PreparedQuery { return new PreparedQuery(this.database, sql); }
transaction<T>(action: () => T): T {
this.database.exec('BEGIN IMMEDIATE');
try { const result = action(); this.database.exec('COMMIT'); return result; }
catch (error) { this.database.exec('ROLLBACK'); throw error; }
}
close(): void { this.database.close(); }
}
const databases = new Map<string, AppDatabase>();
function migrate(database: DatabaseSync): void {
database.exec('BEGIN IMMEDIATE');
try {
const version = Number((database.prepare('PRAGMA user_version').get() as { user_version: number }).user_version);
if (version > 3) throw new Error('数据库版本比当前应用更新,请使用匹配的应用版本。');
if (version < 1) {
database.exec(`
CREATE TABLE IF NOT EXISTS demands (
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, payload TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS demands_owner_updated ON demands(owner_id, updated_at DESC);
CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY, username TEXT NOT NULL COLLATE NOCASE UNIQUE,
display_name TEXT NOT NULL, password_hash TEXT NOT NULL,
role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
disabled INTEGER NOT NULL DEFAULT 0 CHECK(disabled IN (0, 1)),
must_change_password INTEGER NOT NULL DEFAULT 1 CHECK(must_change_password IN (0, 1)),
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, last_login_at TEXT
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_account ON sessions(account_id);
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);
CREATE TABLE IF NOT EXISTS login_limits (
key TEXT PRIMARY KEY, window_start INTEGER NOT NULL, attempts INTEGER NOT NULL
);
PRAGMA user_version = 1;
`);
}
if (version < 2) {
database.exec(`
CREATE TABLE IF NOT EXISTS attachments (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES accounts(id),
demand_id TEXT REFERENCES demands(id),
name TEXT NOT NULL,
size INTEGER NOT NULL CHECK(size > 0 AND size <= 20971520),
content BLOB NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS attachments_demand ON attachments(demand_id);
CREATE INDEX IF NOT EXISTS attachments_owner_staged ON attachments(owner_id, demand_id, created_at);
PRAGMA user_version = 2;
`);
}
if (version < 3) {
database.exec(`
CREATE TABLE feishu_identities (
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
app_id TEXT NOT NULL, tenant_key TEXT NOT NULL, open_id TEXT NOT NULL,
name TEXT NOT NULL, bound_at TEXT NOT NULL,
UNIQUE(app_id, tenant_key, open_id)
);
CREATE TABLE feishu_oauth_states (
state_hash TEXT PRIMARY KEY, browser_hash TEXT NOT NULL,
account_id TEXT REFERENCES accounts(id) ON DELETE CASCADE,
session_hash TEXT, app_id TEXT NOT NULL, verifier TEXT NOT NULL,
return_to TEXT NOT NULL, expires_at INTEGER NOT NULL
);
CREATE INDEX feishu_oauth_expiry ON feishu_oauth_states(expires_at);
CREATE TABLE feishu_notifications (
id TEXT PRIMARY KEY, demand_id TEXT NOT NULL REFERENCES demands(id),
revision INTEGER NOT NULL, target_key TEXT NOT NULL, content TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','sending','sent','failed')),
attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL,
lease_token TEXT, last_error TEXT, created_at TEXT NOT NULL, sent_at TEXT,
UNIQUE(demand_id, revision, target_key)
);
CREATE INDEX feishu_notifications_due ON feishu_notifications(status, next_attempt_at);
PRAGMA user_version = 3;
`);
}
const count = Number((database.prepare('SELECT COUNT(*) AS count FROM accounts').get() as { count: number }).count);
if (count === 0) {
const username = process.env.INITIAL_ADMIN_USERNAME;
const password = process.env.INITIAL_ADMIN_PASSWORD;
if (!username || !password) throw new Error('首次启动请设置 INITIAL_ADMIN_USERNAME 和 INITIAL_ADMIN_PASSWORD(至少 12 位)。');
const now = new Date().toISOString();
database.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
VALUES (?, ?, ?, ?, 'admin', 1, ?, ?)`).run(randomUUID(), normalizeUsername(username), normalizeDisplayName(process.env.INITIAL_ADMIN_DISPLAY_NAME || '系统管理员'), hashPasswordSync(password), now, now);
}
database.exec('COMMIT');
} catch (error) { database.exec('ROLLBACK'); throw error; }
}
// Lazy initialization is intentional: Next.js builds never open or bootstrap a database.
export function getDatabase(): AppDatabase {
applicationOrigin();
const directory = resolve(process.env.DATA_DIR || './data');
const filename = join(directory, 'demand-center.sqlite');
const existing = databases.get(filename);
if (existing) return existing;
mkdirSync(directory, { recursive: true, mode: 0o700 });
const native = new DatabaseSync(filename);
try {
chmodSync(filename, 0o600);
native.exec('PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;');
migrate(native);
const adapter = new AppDatabase(native);
databases.set(filename, adapter);
return adapter;
} catch (error) { native.close(); throw error; }
}
/** Close connections for isolated test processes and graceful maintenance tooling. */
export function closeDatabases(): void {
for (const database of databases.values()) database.close();
databases.clear();
}
+22
View File
@@ -0,0 +1,22 @@
import type { Demand } from '../demand.ts';
import { getDatabase } from './database.ts';
import { AuthError, type AuthUser } from './auth.ts';
/** Resolve missing assignments without rewriting existing responsibilities or history. */
export function withDefaultDeveloper(demand: Demand): Demand {
if (demand.review || ['草稿', '已取消', '已完成'].includes(demand.status)) return demand;
const admin = getDatabase().prepare(`SELECT id, username, display_name FROM accounts
WHERE role = 'admin' AND disabled = 0 ORDER BY created_at, id LIMIT 1`)
.first<{ id: string; username: string; display_name: string }>();
if (!admin) throw new AuthError('暂无启用的系统管理员,请联系管理员恢复账号后重试。', 503);
return { ...demand, review: { developer: { userId: admin.id, username: admin.username, displayName: admin.display_name }, proposals: [] } };
}
/** A read-only administrator can only recover an unavailable developer's assignment. */
export function canTakeOverDevelopment(demand: Demand, user: AuthUser): boolean {
if (user.role !== 'admin' || !demand.review || ['草稿', '已取消'].includes(demand.status) || demand.review.developer.userId === user.userId) return false;
return Boolean(getDatabase().prepare(`SELECT 1 FROM accounts
WHERE id = ? AND role = 'admin' AND disabled = 0 AND must_change_password = 0
AND NOT EXISTS (SELECT 1 FROM accounts WHERE id = ? AND disabled = 0)`)
.bind(user.userId, demand.review.developer.userId).first());
}
+11
View File
@@ -0,0 +1,11 @@
import type { AuthUser } from './auth.ts';
export type DemandViewer = Pick<AuthUser, 'userId' | 'role'>;
// Read access only: admin visibility must never grant business/developer writes.
// The owner can read drafts; everyone else's access requires a formal demand.
export const readableDemandWhere = "(owner_id = ? OR (json_extract(payload, '$.status') != '草稿' AND (? = 1 OR json_extract(payload, '$.review.developer.userId') = ?)))";
export function readableDemandBindings(user: DemandViewer): [string, number, string] {
return [user.userId, user.role === 'admin' ? 1 : 0, user.userId];
}
+80
View File
@@ -0,0 +1,80 @@
import { z } from 'zod';
import { currentProposal, invalidateProposal, type ReviewPerson } from '../demand-review.ts';
import type { Demand } from '../demand.ts';
import { AuthError, type AuthUser } from './auth.ts';
import { getDatabase } from './database.ts';
import { pendingChange } from '../workflow.ts';
import { canTakeOverDevelopment } from './default-developer.ts';
const proposalSchema = z.object({
scope: z.string().trim().min(1).max(6000),
outOfScope: z.string().trim().min(1).max(3000),
});
const person = (user: AuthUser): ReviewPerson => ({ userId: user.userId, username: user.username, displayName: user.displayName });
function changeDeveloper(d: Demand, developer: ReviewPerson, now: string): void {
invalidateProposal(d, now, '开发责任人已变更,需重新提出方案并确认。');
d.status = '待评审';
if (d.acceptance) {
d.acceptance.withdrawnAt = now;
const round = d.delivery?.testing?.find(item => item.round === d.acceptance?.round);
if (round) round.withdrawnAt = now;
}
d.review = { developer, proposals: d.review?.proposals ?? [] };
}
export function applyReviewAction(d: Demand, ownerId: string, user: AuthUser, body: Record<string, unknown>, now: string): { label: string; detail: string } {
if (body.action === 'take-over-development') {
if (!canTakeOverDevelopment(d, user)) throw new AuthError('仅启用的管理员可接手已停用或不可用的开发账号所负责的需求。', 403);
if (pendingChange(d)) throw new AuthError('请先由业务方处理或撤回待确认变更,再接手开发职责。', 409);
if (body.confirm !== true) throw new AuthError('请确认接手开发职责,并重新评审和排期。');
const previous = d.review!.developer;
changeDeveloper(d, person(user), now);
return { label: '接手开发职责', detail: `${previous.displayName}(${previous.username}) → ${user.displayName}(${user.username});原开发账号已停用或不可用。历史方案、计划和验收记录保留,需重新评审、确认计划并提测验收。` };
}
if ((d.status !== '待评审' && (body.action !== 'assign-developer' || ['草稿','已取消'].includes(d.status))) || !d.reviewReady) throw new AuthError('请先补齐业务材料并提交评审。', 409);
const business = ownerId === user.userId;
if (body.action === 'assign-developer') {
if (!business) throw new AuthError('只有需求登记账号可以指定开发责任人。', 403);
if(pendingChange(d))throw new AuthError('请先处理或撤回待确认变更,再更换开发责任人。',409);
if (typeof body.username !== 'string' || !body.username.trim() || body.username.length > 64) throw new AuthError('请填写开发责任人的系统账号。');
const account = getDatabase().prepare('SELECT id, username, display_name FROM accounts WHERE username = ? AND disabled = 0')
.bind(body.username.trim().toLowerCase()).first<{ id: string; username: string; display_name: string }>();
if (!account) throw new AuthError('未找到启用的账号,请核对开发责任人的系统账号。');
if (account.id === ownerId) throw new AuthError('开发责任人与业务确认人须使用不同账号。');
if (account.id === d.review?.developer.userId) throw new AuthError('该账号已是本需求的开发责任人。');
const previous = d.review?.developer;
changeDeveloper(d, { userId: account.id, username: account.username, displayName: account.display_name }, now);
return { label: previous ? '更换开发责任人' : '指定开发责任人', detail: `${previous ? previous.displayName + ' → ' : ''}${account.display_name}(${account.username})。该账号负责后续方案与交付;更换后需重新评审并确认计划。` };
}
if (body.action === 'propose-solution') {
if (d.review?.developer.userId !== user.userId) throw new AuthError('只有当前开发责任人可以提交方案。', 403);
const parsed = proposalSchema.safeParse(body);
if (!parsed.success) throw new AuthError('请填写实施范围与功能说明(6000 字以内)和范围外事项(3000 字以内,无则填“无”)。');
const previous = currentProposal(d);
if (previous && !previous.invalidated && previous.decision?.result !== 'changes_requested') throw new AuthError('当前方案已提交,请等待业务方确认或退回修改。', 409);
const version = (previous?.version ?? 0) + 1;
d.review.proposals.push({ ...parsed.data, version, developer: person(user), submittedAt: now, businessFields: structuredClone(d.fields), businessAttachments: structuredClone(d.attachments ?? []) });
d.fields.scope = parsed.data.scope;
d.fields.outOfScope = parsed.data.outOfScope;
return { label: '提交评审方案', detail: `方案 v${version} 已由 ${user.displayName} 提交,等待业务方确认。` };
}
if (body.action === 'confirm-solution' || body.action === 'return-solution') {
if (!business) throw new AuthError('只有需求登记账号可以代表业务方确认或退回方案。', 403);
const proposal = currentProposal(d);
if (!proposal || proposal.invalidated || proposal.developer.userId !== d.review?.developer.userId || body.proposalVersion !== proposal.version) throw new AuthError('方案已变化,请刷新后核对当前版本。', 409);
const confirming = body.action === 'confirm-solution';
if (proposal.decision && (confirming || proposal.decision.result !== 'confirmed')) throw new AuthError('该版本已处理,请刷新查看最新结果。', 409);
if (confirming && body.confirm !== true) throw new AuthError('请明确勾选同意按当前方案实施。');
const comment = typeof body.comment === 'string' ? body.comment.trim() : '';
if ((!confirming && !comment) || comment.length > 3000) throw new AuthError('请填写修改意见(3000 字以内)。');
// A request to revise an already confirmed version invalidates it without overwriting its original confirmation.
if (proposal.decision?.result === 'confirmed') {
invalidateProposal(d, now, `业务方要求调整:${comment}`);
} else {
proposal.decision = { result: confirming ? 'confirmed' : 'changes_requested', actor: person(user), time: now, comment };
}
return { label: confirming ? '业务方确认方案' : '退回修改方案', detail: `方案 v${proposal.version};${user.displayName} ${confirming ? '同意按此版本实施。' : '要求修改:'}${comment}` };
}
throw new AuthError('不支持的评审操作。');
}
+156
View File
@@ -0,0 +1,156 @@
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { basePath } from '../base-path.ts';
import { safeReturnTo } from '../auth-return.ts';
import type { FeishuBinding } from '../feishu.ts';
import { applicationOrigin, getDatabase } from './database.ts';
import { AuthError, authenticateSession, consumeLoginSourceAttempt, hasAccountPassword, issueIdentitySession, loginWithPassword, revokeSession, type AuthUser } from './auth.ts';
import { feishuJson, feishuLoginConfig } from './feishu-config.ts';
import { PASSWORD_LOGIN_DISABLED } from './password.ts';
const STATE_SECONDS = 600;
const STATE_COOKIE = 'demand_feishu_state';
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
type StateRow = { browser_hash: string; account_id: string | null; session_hash: string | null; app_id: string; verifier: string; return_to: string; expires_at: number };
type Identity = { openId: string; tenantKey: string; name: string };
export class FeishuAuthError extends Error {
code: string;
constructor(code: string) { super(code); this.code = code; }
}
export function requestCookie(request: Request, name: string): string {
return request.headers.get('cookie')?.split(';').map(part => part.trim()).find(part => part.startsWith(name + '='))?.slice(name.length + 1) || '';
}
export function feishuStateCookie(token: string): string {
return `${STATE_COOKIE}=${token}; Path=${basePath || '/'}; HttpOnly; SameSite=Lax; Max-Age=${token ? STATE_SECONDS : 0}${applicationOrigin().startsWith('https://') ? '; Secure' : ''}`;
}
export function beginFeishuAuth(request: Request, intent: string, returnTo: unknown) {
let config;
try { config = feishuLoginConfig(); } catch { throw new FeishuAuthError('unavailable'); }
if (!['login', 'bind'].includes(intent)) throw new FeishuAuthError('failed');
const session = requestCookie(request, 'demand_session');
const user = authenticateSession(session);
if (intent === 'bind' && (!user || user.mustChangePassword)) throw new FeishuAuthError('session');
consumeLoginSourceAttempt(request);
const state = randomBytes(32).toString('base64url');
const browser = randomBytes(32).toString('base64url');
const verifier = randomBytes(32).toString('base64url');
const db = getDatabase();
db.transaction(() => {
db.prepare('DELETE FROM feishu_oauth_states WHERE expires_at <= ?').bind(Date.now()).run();
// A new attempt replaces the previous attempt in this browser.
const previous = requestCookie(request, STATE_COOKIE);
if (previous) db.prepare('DELETE FROM feishu_oauth_states WHERE browser_hash = ?').bind(hash(previous)).run();
db.prepare(`INSERT INTO feishu_oauth_states (state_hash, browser_hash, account_id, session_hash, app_id, verifier, return_to, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).bind(hash(state), hash(browser), intent === 'bind' ? user!.userId : null,
intent === 'bind' ? hash(session) : null, config.appId, verifier, safeReturnTo(returnTo), Date.now() + STATE_SECONDS * 1000).run();
});
const url = new URL('https://accounts.feishu.cn/open-apis/authen/v1/authorize');
url.search = new URLSearchParams({ client_id: config.appId, response_type: 'code', redirect_uri: config.callbackUrl,
state, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' }).toString();
if (intent === 'bind') url.searchParams.set('prompt', 'consent');
return { url: url.href, cookie: feishuStateCookie(browser) };
}
export function consumeFeishuState(request: Request): StateRow {
const state = new URL(request.url).searchParams.get('state') || '';
const browser = requestCookie(request, STATE_COOKIE);
if (![state, browser].every(value => /^[A-Za-z0-9_-]{43}$/.test(value))) throw new FeishuAuthError('expired');
return getDatabase().transaction(() => {
const row = getDatabase().prepare('SELECT * FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).first<StateRow>();
if (!row || row.expires_at <= Date.now() || !timingSafeEqual(Buffer.from(row.browser_hash), Buffer.from(hash(browser)))) throw new FeishuAuthError('expired');
getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE state_hash = ?').bind(hash(state)).run();
return row;
});
}
async function exchangeIdentity(code: string, verifier: string): Promise<Identity> {
const config = feishuLoginConfig();
// The authorize endpoint's PKCE documentation currently pairs it with v2.
// v3 rejected the live app's valid S256 flow with 20049; keep PKCE and use the documented pair.
const token = await feishuJson('https://open.feishu.cn/open-apis/authen/v2/oauth/token', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ grant_type: 'authorization_code', client_id: config.appId, client_secret: config.secret,
code, redirect_uri: config.callbackUrl, code_verifier: verifier }),
});
if (token.code !== undefined && token.code !== 0) throw new FeishuAuthError('failed');
if (typeof token.access_token !== 'string' || !token.access_token) {
console.error('Feishu identity failure', { stage: 'oauth-token', reason: 'missing-access-token' });
throw new FeishuAuthError('failed');
}
const info = await feishuJson('https://open.feishu.cn/open-apis/authen/v1/user_info', { headers: { Authorization: `Bearer ${token.access_token}` } });
const data = info.data as Record<string, unknown> | undefined;
if (info.code !== 0) throw new FeishuAuthError('failed');
const invalidFields = ['open_id', 'tenant_key', 'name'].filter(field => typeof data?.[field] !== 'string' || (data[field] as string).length > 256 || (field !== 'name' && !data[field]));
if (!data || invalidFields.length) {
console.error('Feishu identity failure', { stage: 'user-info', invalidFields });
throw new FeishuAuthError('failed');
}
if (config.tenantKey && data.tenant_key !== config.tenantKey) throw new FeishuAuthError('tenant');
return { openId: data.open_id as string, tenantKey: data.tenant_key as string, name: data.name as string };
}
function bindingUser(request: Request, state: StateRow): AuthUser {
const session = requestCookie(request, 'demand_session');
const current = authenticateSession(session);
if (!current || current.mustChangePassword || current.userId !== state.account_id || hash(session) !== state.session_hash) throw new FeishuAuthError('session');
return current;
}
/** Called inside the identity lookup transaction; roles and usernames never come from browser input. */
function registerFeishuAccount(appId: string, identity: Identity): string {
const db = getDatabase();
const id = randomBytes(16).toString('hex');
const now = new Date().toISOString();
const displayName = identity.name.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 80) || '飞书成员';
db.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
VALUES (?, ?, ?, ?, 'user', 0, ?, ?)`).bind(id, `feishu_${id}`, displayName, PASSWORD_LOGIN_DISABLED, now, now).run();
db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(id, appId, identity.tenantKey, identity.openId, identity.name, now).run();
return id;
}
export async function completeFeishuAuth(request: Request, state: StateRow) {
if (state.app_id !== feishuLoginConfig().appId) throw new FeishuAuthError('expired');
if (state.account_id) bindingUser(request, state);
const params = new URL(request.url).searchParams;
if (params.has('error')) throw new FeishuAuthError('denied');
const code = params.get('code');
if (!code || code.length > 2048) throw new FeishuAuthError('failed');
const identity = await exchangeIdentity(code, state.verifier);
return getDatabase().transaction(() => {
const db = getDatabase();
const bound = db.prepare('SELECT account_id FROM feishu_identities WHERE app_id = ? AND tenant_key = ? AND open_id = ?')
.bind(state.app_id, identity.tenantKey, identity.openId).first<{ account_id: string }>();
if (state.account_id) {
const user = bindingUser(request, state); // Recheck after the network call, including reset/disable/logout.
const existing = db.prepare('SELECT account_id FROM feishu_identities WHERE account_id = ?').bind(user.userId).first();
if ((bound && bound.account_id !== user.userId) || (existing && !bound)) throw new FeishuAuthError('conflict');
if (!bound) db.prepare('INSERT INTO feishu_identities (account_id, app_id, tenant_key, open_id, name, bound_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(user.userId, state.app_id, identity.tenantKey, identity.openId, identity.name, new Date().toISOString()).run();
return { bound: true as const, returnTo: '/account/feishu', token: null, user };
}
const accountId = bound?.account_id ?? registerFeishuAccount(state.app_id, identity);
const result = issueIdentitySession(accountId);
revokeSession(requestCookie(request, 'demand_session'));
return { bound: false as const, returnTo: result.user.mustChangePassword ? '/account/password' : state.return_to, ...result };
});
}
export function getFeishuBinding(accountId: string): FeishuBinding {
const row = getDatabase().prepare('SELECT name, bound_at AS boundAt FROM feishu_identities WHERE account_id = ?').bind(accountId).first<NonNullable<FeishuBinding>>();
return row ? { ...row } : null;
}
export async function unbindFeishu(user: AuthUser, password: unknown, request: Request) {
if (!hasAccountPassword(user.userId)) throw new AuthError('请先设置系统密码,再解除飞书绑定。', 409);
const verified = await loginWithPassword(user.username, password, request);
revokeSession(verified.token);
return getDatabase().transaction(() => {
if (authenticateSession(requestCookie(request, 'demand_session'))?.userId !== user.userId || verified.user.userId !== user.userId) {
throw new AuthError('登录状态已变化,请重新登录。', 401);
}
getDatabase().prepare('DELETE FROM feishu_identities WHERE account_id = ?').bind(user.userId).run();
getDatabase().prepare('DELETE FROM feishu_oauth_states WHERE account_id = ?').bind(user.userId).run();
getDatabase().prepare('DELETE FROM sessions WHERE account_id = ?').bind(user.userId).run();
return issueIdentitySession(user.userId);
});
}
+56
View File
@@ -0,0 +1,56 @@
import { createHash } from 'node:crypto';
import { appPath } from '../base-path.ts';
import { applicationOrigin } from './database.ts';
export function feishuLoginConfigured(): boolean {
return Boolean(process.env.FEISHU_APP_ID?.trim() && process.env.FEISHU_APP_SECRET?.trim());
}
export function feishuCallbackUrl(): string {
return applicationOrigin() + appPath('/api/auth/feishu/callback');
}
export function feishuLoginConfig() {
if (!feishuLoginConfigured()) throw new Error('飞书登录尚未配置 App ID 和 App Secret。');
return {
appId: process.env.FEISHU_APP_ID!.trim(), secret: process.env.FEISHU_APP_SECRET!.trim(),
callbackUrl: feishuCallbackUrl(), tenantKey: process.env.FEISHU_TENANT_KEY?.trim() || '',
};
}
export function feishuBotConfig() {
const webhook = process.env.FEISHU_BOT_WEBHOOK?.trim();
if (!webhook) return null;
let url: URL;
try { url = new URL(webhook); } catch { throw new Error('飞书群机器人 Webhook 地址无效。'); }
if (url.protocol !== 'https:' || url.hostname !== 'open.feishu.cn' || url.port || url.username || url.password || url.search || url.hash || !/^\/open-apis\/bot\/v2\/hook\/[a-zA-Z0-9_-]+$/.test(url.pathname)) {
throw new Error('飞书群机器人地址必须是 https://open.feishu.cn/open-apis/bot/v2/hook/ 开头的完整 Webhook。');
}
return { webhook: url.href, secret: process.env.FEISHU_BOT_SECRET?.trim() || '', targetKey: createHash('sha256').update(url.href).digest('hex') };
}
/** Never expose upstream error text: providers may echo credentials or user information. */
export async function feishuJson(url: string, init: RequestInit): Promise<Record<string, unknown>> {
const stage = ['https://accounts.feishu.cn/oauth/v3/token', 'https://open.feishu.cn/open-apis/authen/v2/oauth/token'].includes(url) ? 'oauth-token'
: url === 'https://open.feishu.cn/open-apis/authen/v1/user_info' ? 'user-info' : 'bot';
let response: Response;
try { response = await fetch(url, { ...init, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(8000) }); }
catch (error) {
console.error('Feishu API failure', { stage, reason: error instanceof Error && error.name === 'TimeoutError' ? 'timeout' : 'network' });
throw new Error('飞书服务连接失败或超时。');
}
let data: unknown;
try { data = await response.json(); }
catch {
console.error('Feishu API failure', { stage, httpStatus: response.status, reason: 'invalid-json' });
throw new Error('飞书服务返回格式无效。');
}
if (!data || typeof data !== 'object' || Array.isArray(data)) {
console.error('Feishu API failure', { stage, httpStatus: response.status, reason: 'invalid-object' });
throw new Error('飞书服务返回格式无效。');
}
const record = data as Record<string, unknown>;
const code = record.code ?? record.StatusCode;
if (!response.ok || (typeof code === 'number' && code !== 0)) {
console.error('Feishu API failure', { stage, httpStatus: response.status, providerCode: typeof code === 'number' ? code : null });
}
if (!response.ok) throw new Error(`飞书服务返回 HTTP ${response.status}。`);
return data as Record<string, unknown>;
}
+178
View File
@@ -0,0 +1,178 @@
import { createHmac, randomUUID } from 'node:crypto';
import type { Demand } from '../demand.ts';
import type { FeishuDelivery, FeishuDeliveryFilter, FeishuStatus } from '../feishu.ts';
import { appPath } from '../base-path.ts';
import { AuthError } from './auth.ts';
import { applicationOrigin, getDatabase } from './database.ts';
import { feishuBotConfig, feishuCallbackUrl, feishuJson, feishuLoginConfigured } from './feishu-config.ts';
const MAX_ATTEMPTS = 5;
type NotificationRow = { id: string; target_key: string; content: string; attempts: number; lease_token: string };
export function signFeishuMessage(timestamp: string, secret: string): string {
return createHmac('sha256', `${timestamp}\n${secret}`).update('').digest('base64');
}
/** Must run inside the demand write transaction so failed writes never generate messages. */
export function queueDemandNotification(demand: Demand): void {
if (demand.status === '草稿') return;
// A malformed notification configuration must not prevent saving a business record.
let config;
try { config = feishuBotConfig(); } catch { return; }
if (!config) return;
const event = demand.history.at(-1);
if (!event) return;
const link = applicationOrigin() + appPath('/?demand=' + encodeURIComponent(demand.id));
const content = [
`需有序 · ${event.action}`, demand.fields.title, `需求:${demand.id} · 第 ${demand.revision} 次保存`,
`当前状态:${demand.status}`, `操作人:${event.actor}`,
`开发责任人:${demand.review?.developer.displayName || '待分配'}`, `时间:${event.time}`, `查看需求:${link}`,
].join('\n');
getDatabase().prepare(`INSERT OR IGNORE INTO feishu_notifications (id, demand_id, revision, target_key, content, next_attempt_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`).bind(randomUUID(), demand.id, demand.revision, config.targetKey, content, Date.now(), new Date().toISOString()).run();
}
async function sendText(content: string): Promise<void> {
const config = feishuBotConfig();
if (!config) throw new Error('尚未配置飞书群机器人。');
const timestamp = String(Math.floor(Date.now() / 1000));
const result = await feishuJson(config.webhook, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ msg_type: 'post', content: plainTextPost(content),
...(config.secret ? { timestamp, sign: signFeishuMessage(timestamp, config.secret) } : {}) }),
});
const code = result.code ?? result.StatusCode;
if (code !== 0) throw new Error(`飞书机器人拒绝消息(错误码 ${typeof code === 'number' ? code : '未知'}),请检查签名、关键词及 IP 限制。`);
}
/** Typed text nodes cannot execute Feishu's text-message <at> markup, including queued legacy messages. */
function plainTextPost(content: string) {
const lines = content.split('\n');
return { post: { zh_cn: { content: lines.map((line, index) => {
const prefix = '查看需求:';
if (index === lines.length - 1 && line.startsWith(prefix)) {
const href = line.slice(prefix.length);
// Only the server-generated final detail link becomes a link node.
if (href.startsWith(applicationOrigin() + appPath('/?demand='))) return [{ tag: 'a', text: '查看需求', href }];
}
return [{ tag: 'text', text: line, un_escape: false }];
}) } } };
}
export async function deliverNextFeishuNotification(): Promise<boolean> {
let config;
try { config = feishuBotConfig(); } catch { return false; }
if (!config) return false;
const db = getDatabase();
const now = Date.now();
const row = db.transaction(() => {
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '机器人地址已变更,旧通知已停止发送。'
WHERE status IN ('pending','sending') AND target_key != ?`).bind(config.targetKey).run();
db.prepare(`UPDATE feishu_notifications SET status = 'failed', lease_token = NULL, last_error = '发送中断且已达到重试上限,请检查后手动重试。'
WHERE status = 'sending' AND next_attempt_at <= ? AND attempts >= ?`).bind(now, MAX_ATTEMPTS).run();
const candidate = db.prepare(`SELECT id FROM feishu_notifications WHERE status IN ('pending','sending') AND next_attempt_at <= ?
AND target_key = ? ORDER BY created_at ASC LIMIT 1`).bind(now, config.targetKey).first<{ id: string }>();
if (!candidate) return null;
const lease = randomUUID();
db.prepare(`UPDATE feishu_notifications SET status = 'sending', attempts = attempts + 1, lease_token = ?, next_attempt_at = ? WHERE id = ?`)
.bind(lease, now + 60_000, candidate.id).run();
return db.prepare('SELECT * FROM feishu_notifications WHERE id = ?').bind(candidate.id).first<NotificationRow>();
});
if (!row) return false;
try {
await sendText(row.content);
db.prepare(`UPDATE feishu_notifications SET status = 'sent', sent_at = ?, last_error = NULL, lease_token = NULL WHERE id = ? AND lease_token = ?`)
.bind(new Date().toISOString(), row.id, row.lease_token).run();
} catch (error) {
// Fetch/network errors can contain a secret URL; retain only our known, sanitized messages.
const message = error instanceof Error && /^飞书(服务返回 HTTP \d+。|机器人拒绝消息(错误码 (\d+|未知)))/.test(error.message)
? error.message : '飞书消息发送失败或超时,请检查网络和机器人配置。';
db.prepare(`UPDATE feishu_notifications SET status = ?, last_error = ?, lease_token = NULL, next_attempt_at = ? WHERE id = ? AND lease_token = ?`)
.bind(row.attempts >= MAX_ATTEMPTS ? 'failed' : 'pending', message, Date.now() + Math.min(30_000 * 2 ** (row.attempts - 1), 15 * 60_000), row.id, row.lease_token).run();
}
return true;
}
type DeliveryCursor = { createdAt: string; id: string };
export type FeishuDeliveryQuery = { filter: FeishuDeliveryFilter; cursor: DeliveryCursor | null };
export function parseFeishuDeliveryQuery(params: URLSearchParams): FeishuDeliveryQuery {
const filter = params.get('filter') || 'all';
if (filter !== 'all' && filter !== 'failed') throw new AuthError('通知筛选条件无效。');
const encoded = params.get('cursor');
let cursor: DeliveryCursor | null = null;
if (encoded) {
try {
if (encoded.length > 512 || !/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Error();
const value: unknown = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
if (!value || typeof value !== 'object' || !('createdAt' in value) || !('id' in value) ||
typeof value.createdAt !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value.createdAt) ||
!Number.isFinite(Date.parse(value.createdAt)) || typeof value.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(value.id)) throw new Error();
cursor = { createdAt: value.createdAt, id: value.id };
} catch { throw new AuthError('通知分页参数无效,请返回第一页后重试。'); }
}
return { filter, cursor };
}
export function feishuStatus(query: FeishuDeliveryQuery = { filter: 'all', cursor: null }): FeishuStatus {
let config = null;
let configurationError = null;
try { config = feishuBotConfig(); } catch (error) { configurationError = (error as Error).message; }
if (Boolean(process.env.FEISHU_APP_ID?.trim()) !== Boolean(process.env.FEISHU_APP_SECRET?.trim())) configurationError = '飞书登录需要同时配置 App ID 和 App Secret。';
const conditions: string[] = [];
const bindings: string[] = [];
if (query.filter === 'failed') conditions.push("status = 'failed'");
if (query.cursor) {
conditions.push('(created_at < ? OR (created_at = ? AND id < ?))');
bindings.push(query.cursor.createdAt, query.cursor.createdAt, query.cursor.id);
}
const rows = getDatabase().prepare(`SELECT id, demand_id AS demandId, revision, status, attempts, last_error AS lastError, created_at AS createdAt, sent_at AS sentAt
FROM feishu_notifications ${conditions.length ? 'WHERE ' + conditions.join(' AND ') : ''}
ORDER BY created_at DESC, id DESC LIMIT 51`).bind(...bindings).all<FeishuDelivery>().results;
const deliveries = rows.slice(0, 50).map(row => ({ ...row }));
const last = deliveries.at(-1);
return {
loginConfigured: feishuLoginConfigured(), callbackUrl: feishuCallbackUrl(), tenantRestricted: Boolean(process.env.FEISHU_TENANT_KEY?.trim()),
botConfigured: Boolean(config), botSigned: Boolean(config?.secret), configurationError,
deliveries, deliveryFilter: query.filter,
nextCursor: rows.length > 50 && last ? Buffer.from(JSON.stringify({ createdAt: last.createdAt, id: last.id })).toString('base64url') : null,
failedCount: getDatabase().prepare("SELECT COUNT(*) AS count FROM feishu_notifications WHERE status = 'failed'").first<{ count: number }>()!.count,
};
}
export function retryFeishuNotification(id: unknown): void {
if (typeof id !== 'string' || id.length > 128) throw new AuthError('通知编号无效。');
const config = feishuBotConfig();
if (!config) throw new AuthError('请先配置群机器人。');
const result = getDatabase().prepare(`UPDATE feishu_notifications SET status = 'pending', attempts = 0, next_attempt_at = ?, last_error = NULL
WHERE id = ? AND status = 'failed' AND target_key = ?`).bind(Date.now(), id, config.targetKey).run();
if (!result.meta.changes) throw new AuthError('只能重试当前机器人发送失败的通知。', 409);
}
export async function testFeishuBot(): Promise<void> {
if (!feishuBotConfig()) throw new AuthError('请先配置群机器人。');
const db = getDatabase();
db.transaction(() => {
const last = db.prepare("SELECT window_start FROM login_limits WHERE key = 'feishu-bot-test'").first<{ window_start: number }>();
if (last && Date.now() - last.window_start < 30_000) throw new AuthError('测试消息每 30 秒可发送一次。', 429);
db.prepare("INSERT OR REPLACE INTO login_limits (key, window_start, attempts) VALUES ('feishu-bot-test', ?, 1)").bind(Date.now()).run();
});
try { await sendText('需有序 · 飞书群机器人连接测试\n收到此消息表示通知通道已连通。'); }
catch { throw new AuthError('测试消息未确认发送成功,请检查 Webhook、签名、关键词、IP 限制及服务器网络。', 502); }
}
let workerStarted = false;
export function startFeishuNotificationWorker(): void {
if (workerStarted || !process.env.FEISHU_BOT_WEBHOOK?.trim()) return;
workerStarted = true;
let busy = false;
const tick = async () => {
if (busy) return;
busy = true;
try { await deliverNextFeishuNotification(); }
catch { console.error('Feishu notification worker could not access the notification queue.'); }
finally { busy = false; }
};
const timer = setInterval(() => { void tick(); }, 3000);
timer.unref();
void tick();
}
+49
View File
@@ -0,0 +1,49 @@
import { randomBytes, scrypt as nativeScrypt, scryptSync, timingSafeEqual } from 'node:crypto';
const COST = 32768;
const OPTIONS = { N: COST, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
const KEY_LENGTH = 64;
// A nonempty, invalid hash also rejects password login on older compatible releases.
export const PASSWORD_LOGIN_DISABLED = '!feishu-only';
export function hasStoredPassword(hash: string | undefined): boolean {
return Boolean(hash) && hash !== PASSWORD_LOGIN_DISABLED;
}
export function validatePassword(password: unknown): asserts password is string {
if (typeof password !== 'string' || password.length < 12 || password.length > 128) {
throw new Error('密码须为 12–128 个字符。');
}
}
function derive(password: string, salt: Buffer): Promise<Buffer> {
return new Promise((resolve, reject) => {
nativeScrypt(password, salt, KEY_LENGTH, OPTIONS, (error, key) => error ? reject(error) : resolve(key));
});
}
function encode(salt: Buffer, key: Buffer): string {
return `scrypt$${COST}$8$1$${salt.toString('hex')}$${key.toString('hex')}`;
}
export async function hashPassword(password: string): Promise<string> {
validatePassword(password);
const salt = randomBytes(16);
return encode(salt, await derive(password, salt));
}
// Only used once while bootstrapping an empty database, within the startup transaction.
export function hashPasswordSync(password: string): string {
validatePassword(password);
const salt = randomBytes(16);
return encode(salt, scryptSync(password, salt, KEY_LENGTH, OPTIONS));
}
export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
if (typeof password !== 'string' || password.length > 128) return false;
const parts = encoded.split('$');
if (parts.length !== 6 || parts[0] !== 'scrypt' || parts[1] !== String(COST) || parts[2] !== '8' || parts[3] !== '1') return false;
if (!/^[a-f0-9]{32}$/.test(parts[4]) || !/^[a-f0-9]{128}$/.test(parts[5])) return false;
const key = await derive(password, Buffer.from(parts[4], 'hex'));
return timingSafeEqual(key, Buffer.from(parts[5], 'hex'));
}
+229
View File
@@ -0,0 +1,229 @@
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import type { Demand } from '../demand.ts';
import { currentProposal, type ReviewPerson } from '../demand-review.ts';
import { changeKey, latestRelease, pendingChange, pendingRecovery, pendingEmergencyVerification, activeIncident, designConfirmed, planConfirmed, unresolvedDefects, type DeliveryPlan, type Release } from '../workflow.ts';
import { AuthError, type AuthUser } from './auth.ts';
export const workflowActions = new Set(['propose-plan','decide-plan','submit-design','decide-design','start-development','update-progress','set-blocker','resolve-blocker','add-note','submit-testing','withdraw-testing','accept','change','assess-change','decide-change','withdraw-change','report-defect','start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral','publish','publish-emergency','verify-emergency','withdraw-recovery','verify-production','request-recovery','decide-recovery','rollback','complete','reopen-incident','retrospective']);
const ownerActions = new Set(['decide-plan','decide-design','accept','change','decide-change','withdraw-change','verify-defect','decide-deferral','decide-recovery','verify-emergency']);
const sharedActions = new Set(['set-blocker','resolve-blocker','add-note','report-defect']);
const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(s => !Number.isNaN(Date.parse(s)) && new Date(s).toISOString().slice(0,10) === s);
const planSchema = z.object({ hours:z.number().positive().max(10000), testDate:dateSchema, feedbackDate:dateSchema, releaseDate:dateSchema, priority:z.enum(['P0','P1','P2']), designRequired:z.boolean(), notes:z.string().trim().min(1).max(3000) }).refine(p=>p.testDate<=p.feedbackDate&&p.feedbackDate<=p.releaseDate);
const checklistSchema = z.array(z.object({id:z.string().trim().min(1).max(30),feature:z.string().trim().min(1).max(200),scenario:z.string().trim().min(1).max(2000),expected:z.string().trim().min(1).max(2000)})).min(1).max(100).refine(rows=>new Set(rows.map(x=>x.id)).size===rows.length);
const person = (user:AuthUser):ReviewPerson => ({userId:user.userId,username:user.username,displayName:user.displayName});
function text(body:Record<string,unknown>,key:string,label:string,max=5000):string {const value=body[key];if(typeof value!=='string'||!value.trim()||value.length>max)throw new AuthError(`请填写${label}(${max}字以内)。`);return value.trim();}
function bool(body:Record<string,unknown>,key:string):boolean {if(typeof body[key]!=='boolean')throw new AuthError('请明确选择处理结果。');return body[key] as boolean;}
function confirm(body:Record<string,unknown>){if(body.confirm!==true)throw new AuthError('请勾选确认后提交。');}
function date(body:Record<string,unknown>,key:string,label:string){const result=dateSchema.safeParse(body[key]);if(!result.success)throw new AuthError(`请填写有效的${label}。`);return result.data;}
function state(d:Demand,allowed:string[]){if(!allowed.includes(d.status))throw new AuthError(`当前处于“${d.status}”,不能执行该操作。`,409);}
function solution(d:Demand){const p=currentProposal(d);if(!d.reviewReady||!p||p.invalidated||p.decision?.result!=='confirmed')throw new AuthError('请先完成当前版本的方案评审与业务确认。',409);return p;}
function forward(d:Demand){if(pendingChange(d))throw new AuthError('存在待处理需求变更,请先完成评估与确认。',409);if(d.blocked)throw new AuthError('需求处于阻塞状态,请先记录处理结果并解除阻塞。',409);}
function planned(d:Demand){solution(d);if(!planConfirmed(d))throw new AuthError('请先由业务方确认当前方案的交付计划。',409);}
function readPlan(d:Demand,body:Record<string,unknown>,user:AuthUser,now:string):DeliveryPlan {const result=planSchema.safeParse(body);if(!result.success)throw new AuthError('请完整填写交付计划;工作量须大于 0,提测日期 ≤ 验收反馈截止日期 ≤ 上线日期。');return {...result.data,developer:d.review!.developer.displayName,version:(d.plan?.version??0)+1,proposalVersion:currentProposal(d)!.version,proposedBy:person(user),proposedAt:now};}
function archivePlan(d:Demand){if(d.plan){d.delivery??={};d.delivery.plans??=[];d.delivery.plans.push(structuredClone(d.plan));}}
function withdrawAcceptance(d:Demand,now:string){if(!d.acceptance)return;d.acceptance.withdrawnAt=now;const round=d.delivery?.testing?.find(x=>x.round===d.acceptance?.round);if(round)round.withdrawnAt=now;}
function exactAcceptance(d:Demand){const a=d.acceptance;const r=d.acceptanceRecords?.at(-1);if(!a||a.withdrawnAt||!r?.passed||r.version!==d.fields.version||r.testVersion!==a.testVersion||(r.round??0)!==(a.round??0))throw new AuthError('当前交付版本尚未通过业务验收,请重新提测并确认。',409);return a;}
export function applyWorkflowAction(d:Demand,ownerId:string,user:AuthUser,body:Record<string,unknown>,now:string):{label:string;detail:string} {
const action=String(body.action);if(!workflowActions.has(action))throw new AuthError('不支持的流程操作。');
const business=user.userId===ownerId,developer=user.userId===d.review?.developer.userId;
if(ownerActions.has(action)?!business:sharedActions.has(action)?!business&&!developer:!developer)throw new AuthError('仅当前需求的对应责任人可以执行此操作。',403);
if(['草稿','已取消'].includes(d.status))throw new AuthError('草稿或已取消需求不能执行交付操作。',409);
if(d.status==='已完成'&&!['report-defect','start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral','request-recovery','decide-recovery','withdraw-recovery','verify-emergency','rollback','reopen-incident','retrospective','add-note'].includes(action))throw new AuthError('需求已归档;线上故障请登记紧急修复,独立新目标请另行登记。',409);
d.delivery??={};const flow=d.delivery,actor=person(user);
const result=(label:string,detail:string)=>({label,detail});
if(action==='propose-plan'){
state(d,['待评审','已排期','开发中']);solution(d);if(pendingChange(d))throw new AuthError('请先处理当前需求变更。',409);
const plan=readPlan(d,body,user,now);archivePlan(d);d.plan=plan;
return result('提出交付计划',`计划 v${plan.version};${plan.hours} 小时,提测 ${plan.testDate},验收反馈 ${plan.feedbackDate},上线 ${plan.releaseDate};等待业务方确认。`);
}
if(action==='decide-plan'){
state(d,['待评审','已排期','开发中']);solution(d);if(pendingChange(d))throw new AuthError('请先处理当前需求变更。',409);
if(!d.plan?.proposedAt||d.plan.decision||body.planVersion!==d.plan.version||d.plan.proposalVersion!==currentProposal(d)!.version)throw new AuthError('计划版本已变化或已处理,请刷新核对。',409);
const approved=bool(body,'approved');confirm(body);const comment=text(body,'comment','排期确认意见',3000);
d.plan.decision={actor,time:now,approved,comment};
if(approved){d.fields.priority=d.plan.priority!;if(d.status==='待评审')d.status='已排期';}
return result(approved?'确认交付计划':'退回交付计划',`计划 v${d.plan.version};${comment}`);
}
if(action==='submit-design'){
state(d,['已排期','开发中']);planned(d);forward(d);
if(!d.plan?.designRequired)throw new AuthError('当前计划不要求设计确认。',409);
if(flow.design){flow.designHistory??=[];flow.designHistory.push(structuredClone(flow.design));}
flow.design={reference:text(body,'reference','设计稿或交互说明链接'),notes:text(body,'notes','设计版本与说明'),actor,time:now,proposalVersion:currentProposal(d)!.version};
return result('提交设计确认',flow.design.reference+';'+flow.design.notes);
}
if(action==='decide-design'){
state(d,['已排期','开发中']);planned(d);forward(d);if(!flow.design||flow.design.decision||flow.design.proposalVersion!==currentProposal(d)!.version)throw new AuthError('当前没有待确认设计。',409);
confirm(body);const approved=bool(body,'approved');flow.design.decision={actor,time:now,approved,comment:text(body,'comment','设计确认意见')};
return result(approved?'确认设计':'退回设计',flow.design.decision.comment);
}
if(action==='start-development'){
state(d,['已排期']);planned(d);forward(d);
if(d.plan!.designRequired&&!designConfirmed(d))throw new AuthError('请先由业务方确认当前方案的设计版本。',409);
confirm(body);flow.kickoff={actor,time:now,technicalPlan:text(body,'technicalPlan','技术方案与代码分支'),dependencies:text(body,'dependencies','依赖、接口与开发准入检查'),design:flow.design?.reference||'计划已确认无需单独设计'};
d.status='开发中';flow.progress={percent:0,notes:'已开始开发',next:'完成开发、自测及代码审查',time:now,actor};
return result('开始开发',flow.kickoff.technicalPlan+';'+flow.kickoff.dependencies);
}
if(action==='update-progress'){
state(d,['开发中']);if(typeof body.percent!=='number'||!Number.isInteger(body.percent)||body.percent<0||body.percent>100)throw new AuthError('进度须为 0–100 的整数。');
flow.progress={percent:body.percent,notes:text(body,'notes','进度说明'),next:text(body,'next','下一步及预计完成时间'),time:now,actor};
return result('更新开发进度',`${body.percent}%:${flow.progress.notes};下一步:${flow.progress.next}`);
}
if(action==='set-blocker'){
if(!['业务方','开发责任人'].includes(String(body.owner))||(body.owner==='开发责任人'&&!d.review))throw new AuthError('请选择阻塞处理责任人。');
flow.blocker={reason:text(body,'reason','阻塞原因'),owner:String(body.owner),dueDate:date(body,'dueDate','跟进日期'),time:now,actor};d.blocked=flow.blocker.reason;
return result('标记阻塞',`${flow.blocker.reason};${flow.blocker.owner},跟进日期 ${flow.blocker.dueDate}`);
}
if(action==='resolve-blocker'){
if(!d.blocked)throw new AuthError('当前没有阻塞事项。',409);const notes=text(body,'notes','阻塞处理结果');delete flow.blocker;delete d.blocked;return result('解除阻塞',notes);
}
if(action==='add-note')return result('补充协作记录',text(body,'notes','进展、沟通结论或资料链接'));
if(action==='submit-testing'){
state(d,['开发中']);planned(d);forward(d);
if(d.plan?.designRequired&&!designConfirmed(d))throw new AuthError('请先确认当前设计版本。',409);
if(unresolvedDefects(d).some(x=>x.blocking&&['待处理','修复中','待确认遗留'].includes(x.status)))throw new AuthError('仍有未修复的阻断缺陷,请先修复后提测。',409);
const parsed=checklistSchema.safeParse(body.items);if(!parsed.success)throw new AuthError('请填写 1–100 条完整且编号唯一的验收项。');
const testVersion=text(body,'testVersion','测试版本或提交号',100);if(flow.testing?.some(x=>x.testVersion===testVersion))throw new AuthError('该测试版本已提测,请使用可追溯的新版本或提交号。',409);
const environment=text(body,'environment','测试环境地址',2000);try{const u=new URL(environment);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)throw new Error();}catch{throw new AuthError('测试环境须为不含账号密码的 HTTP 或 HTTPS 地址。');}
confirm(body);const a={testVersion,environment,deadline:date(body,'deadline','验收截止日期'),items:parsed.data,instructions:text(body,'instructions','操作及测试数据说明'),selfTest:text(body,'selfTest','自测结果'),codeReview:text(body,'codeReview','代码审查结论与记录'),integration:text(body,'integration','集成验证与已知问题'),round:(flow.testing?.length??0)+1,documentVersion:d.fields.version,actor,time:now};
d.acceptance=a;flow.testing??=[];flow.testing.push(structuredClone(a));d.status='待验收';
return result('提交业务验收',`第 ${a.round} 轮,测试版本 ${a.testVersion};文档 ${d.fields.version};${a.items.length} 项,截止 ${a.deadline}。`);
}
if(action==='withdraw-testing'){
state(d,['待验收','待发布']);const reason=text(body,'reason','撤回提测原因');withdrawAcceptance(d,now);d.status='开发中';return result('撤回交付版本',reason+';原验收记录保留,重新提测后需重新验收。');
}
if(action==='accept'){
state(d,['待验收']);forward(d);const a=d.acceptance;if(!a||a.withdrawnAt)throw new AuthError('当前没有有效验收清单。',409);
if(body.testVersion!==a.testVersion||body.version!==d.fields.version||(a.documentVersion&&a.documentVersion!==d.fields.version)||(a.round&&body.round!==a.round))throw new AuthError('验收版本已变化,请刷新核对。',409);
const values=body.results;if(!Array.isArray(values)||values.length!==a.items.length||!values.length||values.some(x=>!['通过','不通过'].includes(x)))throw new AuthError('请逐项填写验收结果。');
confirm(body);const notes=text(body,'notes','遗留问题、证据及处理计划');const passed=values.every(x=>x==='通过');
if(passed&&unresolvedDefects(d).some(x=>x.blocking))throw new AuthError('阻断缺陷尚未复验关闭,不能确认验收通过。',409);
d.acceptanceRecords??=[];d.acceptanceRecords.push({time:now,actor:user.displayName,version:d.fields.version,testVersion:a.testVersion,round:a.round,results:values,notes,passed,items:a.items.map((item,i)=>({...item,result:values[i]})),environment:a.environment});d.status=passed?'待发布':'开发中';
return result(passed?'业务验收通过':'业务验收未通过',`测试 ${a.testVersion} / 文档 ${d.fields.version};${notes}`);
}
if(action==='change'){
state(d,['已排期','开发中','待验收','待发布','已上线']);if(pendingChange(d))throw new AuthError('请先处理已有变更,避免并行改写范围。',409);
const content=text(body,'content','变更内容'),reason=text(body,'reason','变更原因',3000);
d.changes.push({id:randomUUID(),time:now,content,reason,actor:user.displayName,status:'待开发评估',originalVersion:d.fields.version,originalFields:structuredClone(d.fields),originalStatus:d.status});
return result('提出需求变更',content+';'+reason+'。后续流转暂停,等待开发评估与业务确认。');
}
if(['assess-change','decide-change','withdraw-change'].includes(action)){
const c=pendingChange(d);if(!c||changeKey(d,c)!==body.changeId)throw new AuthError('待处理变更已变化,请刷新。',409);
if(action==='withdraw-change'){c.status='已撤回';c.decision={actor,time:now,approved:false,comment:text(body,'comment','撤回原因')};return result('撤回需求变更',c.decision.comment);}
if(action==='assess-change'){
if(c.status==='待业务确认')throw new AuthError('评估已提交,等待业务方确认。',409);solution(d);
const version=text(body,'version','变更后文档版本',100);if(version===d.fields.version)throw new AuthError('变更后须使用新的文档版本。');
c.assessment={time:now,actor,impact:text(body,'impact','工作量、风险及依赖影响'),fields:{...d.fields,scope:text(body,'scope','调整后实施范围',6000),outOfScope:text(body,'outOfScope','调整后范围外事项',3000),criteria:text(body,'criteria','调整后验收标准',6000),version},plan:readPlan(d,body,user,now)};c.status='待业务确认';
return result('提交变更评估',c.assessment.impact+';调整后版本 '+version+',等待业务方确认。');
}
if(!c.assessment||c.status!=='待业务确认')throw new AuthError('请先由开发责任人提交变更评估。',409);
confirm(body);const approved=bool(body,'approved');c.decision={actor,time:now,approved,comment:text(body,'comment','变更确认意见')};c.status=approved?'已确认':'已拒绝';
if(approved){
solution(d);archivePlan(d);d.fields=structuredClone(c.assessment.fields);d.fields.priority=c.assessment.plan.priority!;const version=(currentProposal(d)?.version??0)+1;
d.review!.proposals.push({version,scope:d.fields.scope,outOfScope:d.fields.outOfScope,developer:c.assessment.actor,submittedAt:c.assessment.time,businessFields:structuredClone(d.fields),businessAttachments:structuredClone(d.attachments??[]),decision:{result:'confirmed',actor,time:now,comment:'业务确认变更:'+c.decision.comment}});
d.plan={...c.assessment.plan,proposalVersion:version,decision:c.decision};d.fields.priority=d.plan.priority!;d.status='已排期';withdrawAcceptance(d,now);delete d.acceptance;delete flow.kickoff;delete flow.progress;
}
return result(approved?'确认需求变更':'拒绝需求变更',c.decision.comment+(approved?';范围及计划已同步,重新开发并提测验收。':';原范围及计划继续有效。'));
}
if(action==='report-defect'){
const defect={id:'DEF-'+randomUUID().slice(0,8).toUpperCase(),title:text(body,'title','缺陷标题',200),steps:text(body,'steps','复现步骤'),expected:text(body,'expected','预期结果'),actual:text(body,'actual','实际结果'),evidence:text(body,'evidence','证据或日志链接'),version:text(body,'version','发现版本',100),blocking:bool(body,'blocking'),reporter:actor,time:now,status:'待处理' as const,events:[]};flow.defects??=[];flow.defects.push(defect);
return result('登记缺陷',`${defect.id} ${defect.title};${defect.blocking?'阻断交付':'一般问题'}。`);
}
if(['start-defect','resolve-defect','verify-defect','defer-defect','decide-deferral'].includes(action)){
const defect=flow.defects?.find(x=>x.id===body.defectId);if(!defect)throw new AuthError('找不到该缺陷。',404);
const notes=text(body,'notes','处理说明');let label='';
if(action==='start-defect'){if(!['待处理','已确认遗留'].includes(defect.status))throw new AuthError('该缺陷不在待处理状态。',409);defect.status='修复中';label='开始修复缺陷';}
if(action==='resolve-defect'){if(!['待处理','修复中','已确认遗留'].includes(defect.status))throw new AuthError('该缺陷不能重复提交修复。',409);defect.resolution=notes;defect.fixVersion=text(body,'fixVersion','修复版本',100);defect.status='待复验';label='提交缺陷复验';if(['待验收','待发布','已上线','已完成'].includes(d.status)){if(['已上线','已完成'].includes(d.status)){flow.incidents??=[];flow.incidents.push({id:randomUUID(),time:now,actor,impact:defect.title,reason:notes,releaseId:latestRelease(d)?.id});}d.status='开发中';withdrawAcceptance(d,now);}}
if(action==='verify-defect'){if(defect.status!=='待复验')throw new AuthError('请先由开发提交缺陷修复。',409);confirm(body);const passed=bool(body,'approved');defect.status=passed?'已关闭':'修复中';label=passed?'复验关闭缺陷':'缺陷复验未通过';}
if(action==='defer-defect'){if(defect.blocking||!['待处理','修复中'].includes(defect.status))throw new AuthError('仅未处理的一般缺陷可以申请遗留,阻断缺陷必须修复。',409);defect.resolution=notes;defect.dueDate=date(body,'dueDate','遗留问题计划完成日期');defect.status='待确认遗留';label='申请保留一般缺陷';}
if(action==='decide-deferral'){if(defect.status!=='待确认遗留'||defect.blocking)throw new AuthError('当前没有可确认的遗留申请。',409);confirm(body);const approved=bool(body,'approved');defect.status=approved?'已确认遗留':'修复中';label=approved?'确认遗留问题计划':'拒绝遗留申请';}
defect.events.push({time:now,actor,action:label,notes});return result(label,`${defect.id};${notes}${action==='resolve-defect'?';修复后请使用新的测试版本重新提测。':''}`);
}
if(action==='publish'||action==='publish-emergency'){
const urgent=action==='publish-emergency';
state(d,urgent?['开发中','待验收','待发布']:['待发布']);forward(d);
if(pendingRecovery(d))throw new AuthError('存在待处理的数据恢复申请,请先确认或撤回,再登记新发布。',409);
let version:string,acceptanceRound=0,emergency:Release['emergency'];
if(urgent){
const base=latestRelease(d),incident=activeIncident(d),proposal=solution(d);
if(!base||!incident)throw new AuthError('请先针对已有线上版本登记故障并启动修复。',409);
if(base.documentVersion!==d.fields.version||base.proposalVersion!==proposal.version)throw new AuthError('当前范围或方案已变化,请完成常规业务验收后发布。',409);
for(const key of ['businessRulesUnchanged','scopeUnchanged','noIrreversibleData'])if(body[key]!==true)throw new AuthError('紧急入口仅适用于业务规则及范围不变、且不涉及不可逆数据处理的修复;其他情况须先完成业务确认与常规验收。',409);
if(unresolvedDefects(d).some(x=>x.blocking&&x.status!=='待复验'))throw new AuthError('阻断缺陷仍未修复,不能紧急发布。',409);
version=text(body,'version','紧急发布版本',100);
if(flow.releases?.some(r=>r.version===version)||d.acceptanceRecords?.some(r=>r.testVersion===version&&!r.passed))throw new AuthError('请使用新的、未被业务验收判定不通过的修复版本。',409);
const followUpDate=date(body,'followUpDate','后续业务验证日期');
if(followUpDate<new Date(now).toLocaleDateString('sv-SE',{timeZone:'Asia/Shanghai'}))throw new AuthError('后续业务验证日期不能早于今天。');
emergency={incidentId:incident.id,reason:text(body,'emergencyReason','紧急发布原因'),fixSummary:text(body,'fixSummary','修复内容及影响评估'),selfTest:text(body,'selfTest','自测与关键流程验证'),codeReview:text(body,'codeReview','代码审查及确认记录'),integration:text(body,'integration','构建、集成及关联回归记录'),knownIssues:text(body,'knownIssues','已知问题及风险处理'),followUpPlan:text(body,'followUpPlan','修复同步、记录补充及后续业务验证安排'),followUpDate};
}else{
planned(d);const a=exactAcceptance(d);
if(unresolvedDefects(d).length)throw new AuthError('存在未关闭或未经业务确认的遗留缺陷,不能发布。',409);
if(body.version!==a.testVersion)throw new AuthError('发布版本必须与已验收的测试版本一致。',409);
version=a.testVersion;acceptanceRound=a.round??0;
}
for(const key of ['testsPassed','configurationReady','recoveryReady','noticeComplete'])if(body[key]!==true)throw new AuthError('请逐项完成发布前检查。');confirm(body);
const observationMinutes=body.observationMinutes;if(typeof observationMinutes!=='number'||!Number.isInteger(observationMinutes)||observationMinutes<15||observationMinutes>10080)throw new AuthError('观察时长须为 15–10080 分钟。');
const release:Release={id:randomUUID(),version,previousVersion:text(body,'previousVersion','上一稳定版本',100),time:now,actor,acceptanceRound,documentVersion:d.fields.version,proposalVersion:currentProposal(d)!.version,rollbackPlan:text(body,'rollbackPlan','回滚与恢复方案'),backup:text(body,'backup','备份与数据库兼容性检查'),deployment:text(body,'deployment','实际发布操作及结果'),verificationPlan:text(body,'verificationPlan','生产验证与监控方式'),observationMinutes,observeUntil:new Date(Date.parse(now)+observationMinutes*60000).toISOString(),...(emergency?{emergency}:{})};
if(urgent)withdrawAcceptance(d,now);
flow.releases??=[];flow.releases.push(release);d.status='已上线';return result(urgent?'登记紧急生产发布':'登记生产发布',`版本 ${release.version};观察至 ${release.observeUntil};${release.deployment}${emergency?';待业务方于 '+emergency.followUpDate+' 前补充验证。':''}`);
}
if(action==='verify-emergency'){
const release=flow.releases?.find(r=>r.id===body.releaseId);
if(!release?.emergency||release.rollback||release.emergency.followUp)throw new AuthError('该紧急发布没有待补充的业务验证,请刷新核对。',409);
confirm(body);const approved=bool(body,'approved'),comment=text(body,'comment','业务验证结果与证据');
release.emergency.followUp={actor,time:now,approved,comment};
if(!approved&&release.id===latestRelease(d)?.id&&d.status==='已上线'){
d.status='开发中';withdrawAcceptance(d,now);flow.incidents??=[];
flow.incidents.push({id:randomUUID(),releaseId:release.id,time:now,actor,impact:'紧急发布业务验证未通过',reason:comment});
}
return result(approved?'紧急发布业务验证通过':'紧急发布业务验证未通过',`版本 ${release.version};${comment}`);
}
if(action==='verify-production'){
state(d,['已上线']);const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('没有可验证的当前发布版本。',409);
confirm(body);release.verification={actor,time:now,passed:bool(body,'approved'),results:text(body,'results','核心功能、数据与监控验证结果')};
return result(release.verification.passed?'生产验证通过':'生产验证未通过',`${release.version};${release.verification.results}`);
}
if(action==='request-recovery'){
const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('当前没有可恢复的发布记录。',409);
if(pendingRecovery(d))throw new AuthError('已有数据恢复申请,请等待业务确认。',409);
release.recoveryRequest={actor,time:now,targetVersion:text(body,'targetVersion','恢复目标版本',100),plan:text(body,'plan','数据恢复及增量保留方案'),dataImpact:text(body,'dataImpact','对现有业务数据的影响')};
return result('申请数据恢复确认',`发布 ${release.version} → 恢复目标 ${release.recoveryRequest.targetVersion};${release.recoveryRequest.dataImpact};${release.recoveryRequest.plan}`);
}
if(action==='decide-recovery'||action==='withdraw-recovery'){
const release=body.releaseId?flow.releases?.find(r=>r.id===body.releaseId):pendingRecovery(d),request=release?.recoveryRequest;
if(!request||request.decision||request.withdrawn||release?.rollback)throw new AuthError('没有待确认的数据恢复申请。',409);
if(action==='withdraw-recovery'){
request.withdrawn={actor,time:now,reason:text(body,'reason','撤回恢复申请的原因')};
return result('撤回数据恢复申请',`发布 ${release!.version},恢复目标 ${request.targetVersion};${request.withdrawn.reason}`);
}
confirm(body);const approved=bool(body,'approved');
if(approved&&release!.id!==latestRelease(d)?.id)throw new AuthError('原发布已被新版本替代,请退回旧申请后针对当前版本重新申请。',409);
request.decision={actor,time:now,approved,comment:text(body,'comment','数据恢复确认意见')};return result(approved?'确认数据恢复方案':'拒绝数据恢复方案',`发布 ${release!.version},恢复目标 ${request.targetVersion};${request.decision.comment}`);
}
if(action==='rollback'){
const release=latestRelease(d);if(!release||release.rollback)throw new AuthError('当前版本已经回滚或没有发布记录。',409);
const dataRestored=bool(body,'dataRestored'),runningVersion=text(body,'runningVersion','恢复后的实际运行版本',100);
if(dataRestored&&(!release.recoveryRequest?.decision?.approved||release.recoveryRequest.withdrawn||release.recoveryRequest.targetVersion!==runningVersion))throw new AuthError('涉及数据恢复时,须先由业务方确认对应目标版本和增量保留方案。',409);
confirm(body);release.rollback={actor,time:now,reason:text(body,'reason','回滚原因与影响'),runningVersion,verification:text(body,'verification','恢复后的验证结果'),dataRestored};if(release.recoveryRequest&&!release.recoveryRequest.decision&&!release.recoveryRequest.withdrawn)release.recoveryRequest.decision={actor,time:now,approved:false,comment:'此次仅回滚代码,未执行数据恢复,原申请已结束。'};if(d.status!=='待评审'&&d.status!=='已排期')d.status='开发中';withdrawAcceptance(d,now);
if(!activeIncident(d)){flow.incidents??=[];flow.incidents.push({id:randomUUID(),releaseId:release.id,time:now,actor,impact:release.rollback.reason,reason:'回滚后启动修复'});}
return result('登记回滚与恢复',`${release.version} → ${runningVersion};${release.rollback.reason};${release.rollback.verification}。修复后须重新提测验收。`);
}
if(action==='complete'){
state(d,['已上线']);forward(d);const release=latestRelease(d);
if(release?.emergency){solution(d);if(!release.emergency.followUp?.approved)throw new AuthError('请先由业务方完成紧急发布后的业务验证。',409);}else{planned(d);exactAcceptance(d);}
if(pendingEmergencyVerification(d))throw new AuthError('仍有紧急发布待补充业务验证,请先完成。',409);
if(!release||release.rollback||!release.verification?.passed||release.documentVersion!==d.fields.version||(release.proposalVersion!==undefined&&release.proposalVersion!==currentProposal(d)?.version)||(!release.emergency&&release.version!==d.acceptance!.testVersion))throw new AuthError('请先完成当前发布版本的生产验证。',409);
if(Date.parse(now)<Date.parse(release.observeUntil))throw new AuthError('尚未达到约定观察结束时间,不能归档完成。',409);
if(unresolvedDefects(d).length)throw new AuthError('请先关闭缺陷或完成遗留事项确认。',409);
if(pendingRecovery(d))throw new AuthError('请先处理待确认的数据恢复申请。',409);
confirm(body);release.completion={actor,time:now,handover:text(body,'handover','交接资料及业务通知记录'),monitoring:text(body,'monitoring','监控、故障联系人和告警渠道'),summary:text(body,'summary','观察结论与交付总结')};d.status='已完成';return result('交付完成并归档',release.completion.summary+';交接:'+release.completion.handover+';监控:'+release.completion.monitoring);
}
if(action==='reopen-incident'){
state(d,['已上线','已完成']);confirm(body);const incident={id:randomUUID(),releaseId:latestRelease(d)?.id,time:now,actor,impact:text(body,'impact','线上故障影响'),reason:text(body,'reason','既有范围内的修复内容')};flow.incidents??=[];flow.incidents.push(incident);d.status='开发中';withdrawAcceptance(d,now);return result('登记线上故障并启动修复',incident.impact+';'+incident.reason+'。原范围不变,修复后重新提测、验收和发布。');
}
if(action==='retrospective'){
const item={time:now,actor,cause:text(body,'cause','原因分析'),actions:text(body,'actions','改进措施'),owner:text(body,'owner','改进责任人',100),dueDate:date(body,'dueDate','改进完成日期')};flow.retrospectives??=[];flow.retrospectives.push(item);return result('记录复盘与改进',`${item.cause};${item.actions};${item.owner},${item.dueDate}`);
}
throw new AuthError('不支持的流程操作。');
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more