diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..78e5392 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,35 @@ +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 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5d8630e --- /dev/null +++ b/.env.example @@ -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= diff --git a/.gitignore b/.gitignore index f94cfad..832b976 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,14 @@ 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 diff --git a/.openai/hosting.json b/.openai/hosting.json deleted file mode 100644 index dad4130..0000000 --- a/.openai/hosting.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "d1": "DB", - "r2": null, - "project_id": "appgprj_6aaa34146070819195304ffeb50f65a8" -} diff --git a/DEPLOYED_TXY.md b/DEPLOYED_TXY.md new file mode 100644 index 0000000..d7f3133 --- /dev/null +++ b/DEPLOYED_TXY.md @@ -0,0 +1,272 @@ +# txy 服务器部署记录 + +最近部署完成日期:2026-09-23。访问地址:https://tap.zhongyuan.online + +## 运行位置 + +- SSH 别名:`txy`,登录用户:`ubuntu`。 +- 项目目录:`/home/ubuntu/demand-center`。 +- 数据库:`/home/ubuntu/demand-center/data/demand-center.sqlite`。 +- 数据库备份:`/home/ubuntu/demand-center/data/backups/`。 +- 正式配置:`/home/ubuntu/demand-center/compose.server.yaml` 和 `.env`。 +- Docker 镜像:`xuyouxu-demand-center:20260923T093554Z-feishu-registration`,运行时 Node.js 24.21.0。 +- 容器:`xuyouxu-demand-center-app-1`,仅绑定 `127.0.0.1:3000`;使用独立域名 `tap.zhongyuan.online` 的 Nginx HTTPS 入口转发根路径。 +- 新域名 Nginx 配置:`/etc/nginx/sites-available/tap.zhongyuan.online`,通过 sites-enabled 同名链接启用。 +- 原域名的 `demand-center-http.conf`、`demand-center-https.conf` 仅负责将旧 `/demands` GET/HEAD 地址跳转到新域名,旧地址的写入请求返回410,避免跨域重放。 +- HTTPS证书:`/etc/letsencrypt/live/tap.zhongyuan.online/`,证书自动续期;续期后通过 `renewal-hooks/deploy/reload-nginx-for-tap` 检查并重载Nginx。 +- Nginx 原配置备份:`/home/ubuntu/demand-center/backups/nginx-ai.zhongyuan.online-20260916-072238.conf`。 + +代码和数据都放在 home 目录下。只有 Nginx 路由片段及其引用放在系统 Nginx 配置目录;没有改动原有业务的路由目标。 + +## 首次使用 + +管理员账号:`admin`。首次密码单独保存在服务器的 `/home/ubuntu/.config/demand-center/INITIAL_ACCESS.txt`,文件权限为600;本机同时保存了「需有序_服务器登录信息.txt」。密码未写入源码或镜像。首次登录须修改密码,再从账号菜单进入「账号管理」,开通其他指定用户。 + +用户使用本系统账号密码,不需要 ChatGPT。账号可被停用和重置,业务记录按账号隔离。 + +## 运维命令 + +```sh +ssh txy +cd /home/ubuntu/demand-center +sudo docker compose -f compose.server.yaml ps +sudo docker compose -f compose.server.yaml logs --tail=100 app +sudo docker compose -f compose.server.yaml restart app +``` + +在线备份: + +```sh +sudo docker compose -f compose.server.yaml exec -T app node scripts/backup.mjs +``` + +更新源码后,仍使用服务器专用 Compose 文件构建和启动,避免误用默认的独立域名配置: + +```sh +sudo docker compose -f compose.server.yaml build app +sudo docker compose -f compose.server.yaml up -d --wait --wait-timeout 60 +``` + +`APP_URL` 是域名 origin:`https://tap.zhongyuan.online`。`NEXT_PUBLIC_BASE_PATH` 为空,编译时和运行时一致,直接使用独立域名根路径。2026-09-16 从旧的 `https://ai.zhongyuan.online/demands` 切换,账号与需求表指纹一致;原账号密码保留,新域名需重新登录。 + +本次域名切换的环境与反向代理回退配置保存在 `/home/ubuntu/demand-center/backups/tap-migration-20260916-073656/`。不要将其中包含密码的环境文件打包或公开。 + +## 验证 + +- 服务器 Docker 构建和 Node.js 24 容器运行通过,容器 healthy。 +- HTTPS 健康接口、登录页和静态资源通过访问检查。 +- 线上电脑1440×1000与手机390×844浏览器验证通过;JS/CSS均从/_next/加载并返回200,无页面错误或横向溢出。 +- 首次管理员登录、必须改密、Secure/HttpOnly/路径范围 Cookie、未登录访问限制、退出会话撤销验证通过。 +- 容器重启后管理员身份保持一致,确认数据目录持久化;验证会话已退出。 +- 在线 SQLite 备份已成功生成;`.env` 和数据库权限600、数据目录权限700。 +- 应用通过生产构建及35项登录、权限、数据隔离与重启集成检查;新独立域名版本已在服务器重新构建并运行验证。 +- 新域名登录来源校验通过,旧域名来源被拒绝;原AI站点根路径和/listing仍返回200。 + +原来的 `chatgpt.site` 演示站与本服务器版本独立,本次没有更改其数据或发布内容。 + +## 关闭按钮修复 + +2026-09-16 修复需求登记窗口:未修改直接关闭,已修改使用居中确认层,不受表单滚动位置影响。继续填写保留内容、步骤、滚动和焦点;保存期间禁止关闭及修改字段。12项桌面/手机行为检查和生产构建通过。回退源码与Compose文件位于服务器 backups/close-button-20260916/。 + +## 演示数据移除 + +2026-09-16 已移除内置的10条示例(含2条草稿)、演示模式及体验入口。工作台只读取当前账号实际保存的需求;没有需求时显示空状态,加载失败时显示重试。数据库检查未发现演示记录,本次未执行数据库删除。10项隔离浏览器检查通过,覆盖加载、错误重试、草稿保存、正式登记、刷新持久化、搜索导航及手机布局。 + +## Review 修复 + +2026-09-16 已发布 `20260916-review-fixes`: + +- 登录额度按可信客户端来源隔离,保留账号防猜密限制;不再使用全体用户共用的拒绝额度。 +- 管理员重置密码会清除目标账号的旧锁定,来源限流仍保留。 +- 迟到的需求加载响应会保留请求期间成功保存的记录,避免新草稿从列表消失。 +- 工作台统计入口会重置旧筛选,“进行中”和“已完成”仍应用对应预设。 + +服务器专用 Compose 显式设置 `LOGIN_CLIENT_IP_HEADER=x-real-ip`。仅 tap 的 HTTPS Nginx 配置启用 Cloudflare 官方网段信任,再覆盖传给应用的 `X-Real-IP`;直连请求提供的同名头或 `CF-Connecting-IP` 无法自行改写来源。网段配置源文件为 `deploy/tap-cloudflare-realip.conf`,2026-09-16 从官方 IPv4/IPv6 列表下载并校验。应用端口继续只绑定 `127.0.0.1:3000`。 + +发布前的源码、Compose、环境、Nginx 配置和在线 SQLite 快照位于 `/home/ubuntu/demand-center-backups/20260916T084826Z-review-fixes/`,目录权限700、备份文件600。回滚优先恢复旧镜像及代理配置,保留当前数据库;本次没有数据库结构迁移。 + +新版通过生产构建、类型检查、14项单元测试、45项HTTP集成检查及6组隔离浏览器回归。服务器容器 healthy,HTTPS健康接口与登录页正常,原AI根站和列表页正常;账号及需求指纹与发布前一致。 + + +## 方案评审与附件功能上线(2026-09-17) + +2026-09-17 11:13(北京时间)切换服务,11:16 完成公网验证。该次发布版本 `20260917T025919Z-review-attachments` 已包含: + +- 实施范围与功能说明、范围外事项移至需求评审,由指定开发账号提出方案、业务登记账号确认或退回;保留方案版本及确认记录。 +- 文件附件上传、移除、鉴权下载、历史评审材料保留与暂存恢复,单文件 20 MB、每条需求最多 10 个。 +- 找回附件后取消或移除不再自动删除原文件;恢复列表加载失败可重试,暂存达到上限时自动刷新并展开列表。 + +数据库自动从版本 1 升至版本 2,新增附件表。上线前先用现有数据副本演练,切换时短暂进入维护状态、停止旧服务并生成最终一致性备份;升级后账号、需求、会话和登录限制表的指纹均与该备份一致。没有创建线上测试账号或业务记录。 + +Nginx 仅调整 `tap.zhongyuan.online` 的请求大小上限,由 `256k` 改为 `22m`。可信代理配置、HTTPS、登录环境和数据挂载保持原配置。 + +验证结果: + +- 服务器实际构建的新镜像通过 129 项隔离 HTTP 集成检查,涵盖方案评审、附件权限、持久化及备份。 +- 数据副本迁移和正式数据库迁移均通过完整性及原表指纹校验。 +- 正式容器为 healthy,仅绑定 `127.0.0.1:3000`;运行日志无异常。 +- 公网 HTTPS 健康接口、登录页和 8 个 JS/CSS 资源均返回 200。 +- 未登录的需求和附件接口返回 401;20 MB 匿名上传探测通过代理,返回应用的 401,未存储测试文件。 +- 原 AI 根站和 `/listing` 返回 200。 + +上线资料: + +- 原源码、环境、Nginx 配置、原镜像标识与数据库快照:`/home/ubuntu/demand-center-backups/20260917T025919Z-review-attachments/`。 +- 最终切换前数据库快照:上述目录的 `cutover.sqlite`,线上副本另位于 `data/backups/cutover-20260917T025919Z-review-attachments.sqlite`。 +- 发布源码、清单与操作日志:`/home/ubuntu/demand-center-releases/20260917T025919Z-review-attachments/`。 +- 源码归档 SHA-256:`6e6e950aa85db785afeafa7a0810a79b70a07d8d27fd40595c5e0e23984579bf`。 +- 该次发布镜像 ID:`sha256:e1dca4ac12eecf18cf3ecc4d083ec0020132776ff588b187a9e3793c0975795a`。 + +Nginx 重载后的首次即时探测短暂返回维护页;随后源站及公网均确认 200,未执行数据库或服务回退。最终发布状态已记录为 complete。 + +本节发布之前的旧版应用仅支持版本 1 数据库,不能仅切回旧镜像连接当前数据库。如需上线后回退,应先备份当前数据,优先使用兼容版本 2 的修复版本;恢复切换前快照前须核对上线后的新增需求和附件,避免覆盖新数据。 + + +## 模板预览与填写入口上线(2026-09-17) + +2026-09-17 14:45(北京时间)切换至 `20260917T063838Z-templates`,随后完成公网验证。包含: + +- 业务背景旁的上传文件、内置模板预览和 Word 下载;支持简短说明及填写后的文档链接。 +- SOP 和 7 份模板在系统内阅读、关联模板跳转及 `.docx` 下载;飞书入口统一指向用户提供的模板总目录。 +- 模板脚本加载失败时在弹窗内提示并允许重试,保留原表单及附件;快速按 Escape 仅关闭预览,并将焦点归还入口。 + +数据库继续使用版本 2,无结构迁移。上线前在线备份,切换时停止旧服务再生成最终快照;新服务启动后,账号、需求、附件、会话与登录限制表的指纹全部一致。未创建线上测试账号或业务记录。Nginx 仅临时提供维护响应,切换完成后恢复并核对原配置,HTTPS、可信代理与 22 MB 请求上限保持原设置。 + +验证结果: + +- 服务器实际构建的新镜像通过 142 项隔离接口检查,覆盖文档预览鉴权、8 份 Word 下载、评审与附件操作等。 +- 现有数据副本启动演练及正式服务切换均通过数据库完整性与各表指纹校验。 +- 本地生产构建、静态检查、原有 6 组模板流程和新增 4 组容错浏览器回归通过。 +- 正式容器 healthy,运行时 Node.js 24.21.0,仅绑定 `127.0.0.1:3000`,运行日志正常。 +- 公网健康接口、登录页及 8 个登录资源返回 200;另核对 2 个模板功能脚本的 SHA-256,公网字节与服务器一致。 +- 未登录的需求、附件、模板预览和 Word 下载均返回 401;原 AI 根站及 `/listing` 返回 200。 + +发布资料: + +- 数据与配置备份:`/home/ubuntu/demand-center-backups/20260917T063838Z-templates/`。 +- 最终切换前快照:上述目录的 `cutover.sqlite`;数据卷内另保留 `data/backups/cutover-20260917T063838Z-templates.sqlite`。 +- 发布源码、清单和操作日志:`/home/ubuntu/demand-center-releases/20260917T063838Z-templates/`。 +- 源码归档 SHA-256:`1f8f4c4025480f0ad16095cdf2d9c2b389414388cde024b707bb846e25d655b8`。 +- 该次发布镜像 ID:`sha256:fbb050fd84a549704faedf569df31e43ba968edb005e28050364254dd54aa463`。 + +Nginx 重载后的首次探测短暂收到维护响应,自动重试后源站及公网均通过;最终状态为 complete,未执行回退。 + +如需回退本次发布,上一版 `20260917T025919Z-review-attachments` 同样支持版本 2 数据库,可恢复备份的 Compose 和旧镜像并保留当前数据库。数据库快照用于故障恢复;使用前应核对上线后的新增内容。 + + +## 管理员需求可见范围上线(2026-09-17) + +2026-09-17 15:17(北京时间)切换至 `20260917T071333Z-admin-visibility`。 + +- 管理员通过侧栏「全部需求」查看所有正式需求及当前、历史评审附件;他人草稿和未保存附件仍私有。 +- 「我的需求」、工作台统计与待办继续只计算本人登记或负责开发的事项。 +- 全局查看不授予编辑、取消、变更、指定开发、提交方案或业务确认权限;明确参与需求时仍按对应职责操作。 + +数据库保持版本 2,无结构迁移。切换前停止旧服务并生成最终一致性快照;新服务启动后,账号、需求、附件、会话及登录限制表的指纹全部一致。没有创建线上测试账号或业务记录。Nginx 在短暂维护后恢复原配置,HTTPS、可信代理、22 MB 请求上限及数据挂载均保持原设置。 + +服务器新镜像通过 174 项隔离接口检查及现有数据副本验证;本地 26 项单元测试、5 组多账号浏览器回归和桌面/手机布局检查通过。正式容器 healthy,运行时 Node.js 24.21.0,仅绑定 `127.0.0.1:3000`,运行日志正常。 + +公网健康接口、登录页及 8 个登录资源返回 200;管理员页面脚本的 SHA-256 与服务器构建一致。未登录的需求、附件、模板预览及 Word 下载接口返回 401。旧 AI 入口首次探测发生一次读取超时,重试后根路径及 `/listing` 均返回 200。公网验证报告已归档为发布目录下的 `public-smoke.json`。 + +发布资料: + +- 数据、源码与配置备份:`/home/ubuntu/demand-center-backups/20260917T071333Z-admin-visibility/`。 +- 最终切换前快照:上述目录的 `cutover.sqlite`;数据卷内另保留 `data/backups/cutover-20260917T071333Z-admin-visibility.sqlite`。 +- 发布源码、清单及日志:`/home/ubuntu/demand-center-releases/20260917T071333Z-admin-visibility/`。 +- 源码归档 SHA-256:`f7e1e733a36ea8144741a01c6ae6378c910bf74a987c8c55628e94c805b6037c`。 +- 该次镜像 ID:`sha256:0ff3c76ffc315ed602900f1eed0b9837c9cbbafb17d9d248ee66ea9cf61ce412`。 + +切换脚本最终状态为 complete,未执行回退。若需回退本次发布,可恢复备份的 Compose 并使用 `20260917T063838Z-templates` 镜像,保留当前版本 2 数据库;回退后管理员将恢复上一版的可见范围。 + + +## 完整交付流程与审查修复上线(2026-09-17) + +2026-09-17 16:52(北京时间)切换至 `20260917T084659Z-full-workflow`,随后完成公网验证。包含: + +- 交付计划与设计确认、开发进度与阻塞、提测及逐项验收、变更审批、缺陷修复复验、发布验证、观察归档、恢复与复盘。 +- 发布始终由当前开发责任人负责。符合条件的线上故障可经技术验证后紧急发布,业务方随后按实际发布版本补充验证,完成前不得归档;常规业务确认与管理员只读权限保留。 +- 数据恢复申请在新发布前必须处理或撤回,历史申请仍可关闭;设计待办校验当前方案并覆盖开发中;验收清单增删不再生成重复编号;紧急发布进度明确显示业务补验。 + +数据库保持版本 2,无表结构迁移。在线备份和切换前最终快照均已生成;停止旧服务后取得最终一致性快照,新容器启动后核对账号、需求、附件、会话和登录限制表的指纹,全部一致。未创建线上测试账号或业务记录。Nginx 在短暂维护后恢复原配置,HTTPS、可信代理、22 MB 请求上限、环境和数据挂载均保持原设置。 + +验证结果: + +- 服务器实际构建的新镜像通过 174 项基础接口检查和 123 项完整交付检查,共 297 项;现有数据库副本启动演练通过。 +- 本地 40 项单元测试、4 组审查修复页面回归、静态检查、TypeScript 与生产构建通过,桌面和手机页面已复核。 +- 线上容器 healthy,Node.js 24.21.0,仅绑定 `127.0.0.1:3000`,启动日志正常;环境、数据库权限600,数据目录700。 +- 公网 HTTPS 健康接口、登录页及 8 个登录静态资源返回200,完整交付功能脚本的 SHA-256 与新镜像一致。 +- 未登录需求、附件、模板预览和 Word 下载接口均返回401;原 AI 根站和 `/listing` 返回200。 + +发布资料: + +- 数据、原源码和配置备份:`/home/ubuntu/demand-center-backups/20260917T084659Z-full-workflow/`。 +- 最终切换快照:上述目录的 `cutover.sqlite`,数据卷内另存 `data/backups/cutover-20260917T084659Z-full-workflow.sqlite`。 +- 源码归档、清单、构建及验证日志、公网验证报告:`/home/ubuntu/demand-center-releases/20260917T084659Z-full-workflow/`。 +- 源码归档 SHA-256:`c9200be6dce565d303a67ac0fd9a66091b0e7645afdab7e0bb21dde20ddf6ff9`。 +- 当前镜像 ID:`sha256:1d3e1fe9137fdedf9e1daa4b456d2b8630c6bd80b4e38519db3b997383147a7c`。 +- 交付页面脚本:`/_next/static/chunks/app/page-10a275f5683b5120.js`;SHA-256:`76a99a4fcad680ed7a713d2366311c08a8adae2c5875dd03889cd1215b3b6ec2`。 + +最终状态为 complete,未执行回退。Nginx 重载后的首次探测短暂收到维护响应,自动重试后源站和公网均通过。上一版镜像与 Compose 已保留,可在需要时切回应用并保留当前数据库;旧版界面不支持新交付流程,上线后已产生新流程记录时应优先向前修复。恢复数据库快照前须核对并保留新增记录。 + + +## 飞书登录与审查修复上线(2026-09-23) + +2026-09-23 16:31(北京时间)切换至 `20260923T081446Z-feishu`。本次启用飞书登录;按用户要求,群机器人暂不配置、不发送通知。 + +- 飞书 OAuth v3、PKCE、一次性 state、原系统账号绑定/解绑、账号停用及原有权限控制已上线。首次使用先通过原账号密码登录,在「飞书绑定」中绑定本人身份。 +- 飞书应用凭证已写入服务器 `.env`(权限600),未写入源码或镜像,临时上传的凭证文件已删除。服务端凭证校验成功。用户补齐正式回调地址后,站点可跳转到正常的飞书扫码授权页面,无20029错误。 +- 飞书与密码登录共用受信来源限流;消息使用纯文本节点防止 at 标签被执行;管理员通知记录支持失败筛选、历史分页及旧记录重试。机器人相关功能保留在代码中,待后续配置 Webhook 后启用。 + +数据库从版本2迁移到版本3,新增飞书绑定、授权状态与通知队列表。上线前在线备份、镜像隔离测试及现有数据副本演练均通过;正式切换时进入短暂维护、停止旧服务并取得最终快照。新服务启动后,账号、需求、附件、会话及登录限制表的指纹与最终快照一致,三个新表初始为空。没有创建线上测试账号或业务记录。 + +服务器实际镜像通过175项基础接口检查、162项完整交付检查、49项飞书接口检查,共386项。飞书测试使用模拟服务与独立临时数据库,网络隔离。此前本地65项单测、静态检查、TypeScript、生产构建及桌面/手机筛选分页重试回归均通过。正式容器 healthy,Node.js 24.21.0,仅绑定 `127.0.0.1:3000`。桌面和手机登录页及真实授权跳转通过浏览器检查,无页面脚本错误;真实用户绑定由用户首次使用时完成。 + +发布资料: + +- 原数据、源码、环境、Compose、Nginx配置与旧镜像标识:`/home/ubuntu/demand-center-backups/20260923T081446Z-feishu/`。 +- 最终一致性快照:上述目录的 `cutover.sqlite`;数据目录内另存 `data/backups/cutover-20260923T081446Z-feishu.sqlite`。 +- 发布源码、文件清单、构建与验证日志:`/home/ubuntu/demand-center-releases/20260923T081446Z-feishu/`。 +- 源码归档 SHA-256:`2c93542ecacdcdb34fa8fc69d4e8c6105dd0c7dca5e9f578df027f39a2fea225`。 +- 镜像 ID:`sha256:0eabc4ca5d8a4c9339d07ec1a321e19d5b1d1cf1330628fc89071add826c6012`。 + +Nginx、HTTPS及受信代理配置在切换后恢复并逐字核对,临时维护响应已解除。最终切换状态为 complete,未执行回退。旧版应用不支持版本3数据库:上线后如需回退,应先保留当前数据库并核对新增数据,不能直接切回旧镜像,也不能未经核对覆盖为旧快照;优先向前修复。 + +## 飞书绑定故障诊断(2026-09-23) + +发现真实绑定在收到授权码后返回通用失败提示,原日志未保留接口错误码。已发布 `20260923T085243Z-feishu-diagnostics`,仅增加飞书接口阶段、HTTP状态、数值错误码及缺失身份字段名称的脱敏诊断,不记录请求体、密钥、授权码、访问令牌或个人信息。 + +此版本不调整授权规则或数据库结构。服务器镜像通过175项基础接口检查及49项飞书接口检查;本地类型检查、15项飞书相关测试、静态检查通过。更新前已备份数据库、源码与配置,正式环境配置保持不变。随后通过真实授权复现确认换令牌接口返回20049(PKCE校验失败),见下节修复记录。 + +发布目录:`/home/ubuntu/demand-center-releases/20260923T085243Z-feishu-diagnostics/`;备份目录:`/home/ubuntu/demand-center-backups/20260923T085243Z-feishu-diagnostics/`。如需回退,可恢复上一版镜像和Compose,保留当前版本3数据库。 + +## 飞书 PKCE 兼容性修复(2026-09-23) + +真实绑定在换取令牌时返回飞书错误20049(PKCE校验失败)。线上授权请求中的S256挑战值与对应数据库验证值核对一致;按飞书授权接口文档的PKCE配套说明,切换至 `authen/v2/oauth/token` 并使用JSON请求体,完整保留 `code_challenge`、S256及 `code_verifier`,不在失败后回退或关闭校验。脱敏诊断继续保留。 + +已发布 `20260923T090143Z-feishu-pkce`,应用与数据库结构不变,原凭证配置保留。服务器镜像通过175项基础接口检查及49项飞书接口检查,后者已校验跨HTTP请求传递的验证值与授权挑战值相匹配;本地15项飞书相关测试、类型检查、静态检查、生产构建及49项接口检查通过。服务健康,用户重新授权后确认绑定成功,真实换令牌、用户身份读取及账号绑定流程已验证通过。 + +发布目录:`/home/ubuntu/demand-center-releases/20260923T090143Z-feishu-pkce/`;备份目录:`/home/ubuntu/demand-center-backups/20260923T090143Z-feishu-pkce/`。源码归档SHA-256:`5dbc26357de35cd616f85f7221a947450c80170af31df5734176f431ad856a99`。如需回退,应保留当前版本3数据库,仅回退镜像和配置;旧v3换令牌行为可能重新遇到20049。 + + +## 飞书首次登录自动注册上线(2026-09-23) + +已发布 `20260923T093554Z-feishu-registration`:新成员首次通过飞书授权后自动注册普通成员账号并进入工作台,无需预先开通或先设置密码。重复及并发登录复用同一账号;已有绑定继续使用原账号、角色和需求,未按姓名或邮箱自动合并。账号停用后仍拒绝登录,不重新注册绕过限制。 + +飞书注册账号以非空、不可验证的密码标记禁用初始密码登录,没有默认或通用密码;旧版本密码校验器也不会将该标记当作有效密码。成员可选设置首份系统密码,设置后撤销旧会话;已有密码的修改继续验证当前密码。解绑须先设置并验证系统密码,原账号和需求保留。数据库仍为版本3,无结构迁移,原飞书凭证、回调及群机器人关闭状态保持不变。 + +验证:67项单测通过;服务器实际镜像通过175项基础接口、162项完整交付、69项飞书接口检查,共406项。桌面与手机浏览器覆盖首次授权自动注册、成员权限、首次密码设置、解绑后的密码登录及通知管理;新增身份验证使用隔离数据库和模拟飞书接口,未创建线上测试账号。真实授权接口沿用已验证成功的v2与S256 PKCE组合。正式容器 healthy,公网健康接口与登录页检查通过。 + +发布目录:`/home/ubuntu/demand-center-releases/20260923T093554Z-feishu-registration/`;备份目录:`/home/ubuntu/demand-center-backups/20260923T093554Z-feishu-registration/`。更新前已备份数据库、源码、Compose和环境。源码归档SHA-256:`90505ffbe76ddd012655b7fdddc42d1598d3312e3b2a042d589f7d87e9fc4c39`。如需回退,保留当前版本3数据库,仅回退镜像与代码;上一版本不提供自动注册和首份密码设置,但既有飞书绑定仍可用于登录。 + + +## 默认开发负责人及两处审查修复上线确认(2026-09-23) + +2026-09-23 18:11(北京时间)核验确认:开发负责人默认系统管理员、停用开发账号的管理员接手入口,以及兼任业务和开发角色时的阻塞待办修复,均已包含在当前运行版本 `20260923T093554Z-feishu-registration` 中。核验时发布清单中的186个文件与本地完全一致,因此本次没有重复构建、切换或重启服务,也没有改动生产业务数据。 + +- 当前运行镜像:`sha256:26aabece487d8fbf6cd88a8b161585c88470de2598bb8db5b4bd77187a324798`,容器 healthy。 +- 运行镜像中已包含默认管理员提示、接手入口及服务端接手操作;该镜像发布日志记录175项基础接口、162项完整交付及69项飞书接口检查通过。 +- 公网业务页面脚本 `/_next/static/chunks/app/page-92b8af160de25007.js` 返回200,SHA-256为 `c538b209026faaf24c6f8d55c18819a98cc6ad1d2afb59e5b5b5e1f1bee7cdee`,与运行容器内文件一致。 +- 公网健康接口和登录页返回200;未登录的需求、附件及Word下载接口返回401。 +- 上次发布的数据、源码及Compose备份存在,当前环境配置与发布前保留的环境配置一致。 + +核验报告保存至当前发布目录的 `default-developer-verification.json`。 diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..39c6856 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,199 @@ +# 自有服务器部署说明 + +本版本使用系统自有账号登录,账号和需求存储在自己的服务器。用户可使用管理员创建的账号;启用飞书后,首次飞书授权登录会自动注册普通成员账号,不需要 GPT 登录。交付的是源码和部署配置;原 `chatgpt.site` 演示地址仍运行原托管版本。 + +已部署的 txy 实例使用独立域名 `https://tap.zhongyuan.online`;其操作命令和配置位置见 [服务器部署记录](DEPLOYED_TXY.md)。以下为通用独立域名部署步骤。 + +## 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`。不要直接将客户端可伪造的转发头当作限流依据。txy 已配置此链路,详见部署记录;更换 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` 写入。 + +原演示站的云端数据不会自动迁入本地 SQLite。本版本已移除内置演示需求,仅显示数据库中的实际记录;按需求授权的开发方案提交与业务确认已提供;开发排期、提测和发布流转后台仍需后续建设。 + +## 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`;服务器文件加 `-f compose.server.yaml`),单纯 restart 不会重新加载 Compose 环境变量。 + +此版本自动迁移数据库到版本 3,新增绑定、授权状态和通知表。上线前备份数据库;回滚到版本 2 应用需要恢复上线前备份,旧代码无法读取版本 3 数据库。 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..846d607 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/FEISHU.md b/FEISHU.md new file mode 100644 index 0000000..15efad8 --- /dev/null +++ b/FEISHU.md @@ -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`,服务器使用 `docker compose -f compose.server.yaml 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 只用于当次读取身份,不落库。当前授权文档明确说明 PKCE 配套使用 v2;本应用真实授权使用 v3 时曾返回 20049,因此使用 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。上线前备份;回滚旧应用须同步恢复兼容的数据库备份。 diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md index d5a0191..0a44fd4 100644 --- a/IMPLEMENTATION.md +++ b/IMPLEMENTATION.md @@ -1,24 +1,103 @@ -# 需有序 · 业务需求登记管理 +# 需有序 · 自部署版本说明 -基于本目录《开发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 配置检查通过;已在 txy 服务器完成实际 Docker 构建和启动,运行时 Node.js 24.21.0,容器 healthy,详见 DEPLOYED_TXY.md。 +- 直接运行版本在本机 Node.js 26 验证;Node.js 24 镜像在 Ubuntu 24.04 服务器实际验证通过。 +- 页面验证使用隔离的无界面浏览器(内置浏览器连接不可用):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 组模板流程回归、静态检查及生产构建继续通过,桌面和手机端错误提示排版复核通过。 + +## 模板使用改进(2026-09-17 已上线) + +- 业务背景填写区增加上传文件、内置模板预览与 Word 下载;允许简短说明,并提供填写完成后的文档链接输入。 +- 业务背景与参考材料两步复用同一附件列表和链接字段,保留既有恢复、移除及保存机制。 +- 基本信息、业务背景、验收标准和数据来源展示对应内置模板;流程与规范集中展示 SOP 和 7 份模板。 +- 用户提供的飞书链接已确认为模板总目录,统一按目录入口展示,并提示先创建副本;不将其标为某一份具体模板,也不自动修改飞书文档。 +- 模板正文在系统内阅读,支持表格与相关模板跳转;Word 文件走现有登录鉴权接口,旧 Markdown 下载地址继续兼容。此次无需数据库迁移。 +- 预览弹窗直接随页面加载,正文渲染模块按需加载并捕获失败;重新加载会重新请求失败的脚本,正文渲染错误也由局部错误边界承接,不卸载登记表。表单同步记录预览打开状态,避免弹窗初始化期间 Escape 误触发退出,关闭后将焦点归还入口按钮。 + +## 使用边界 + +当前源代码包含业务端、账号管理、方案评审及完整交付流程,操作职责和准入条件见 README.md。发布和回滚操作登记实际执行结果,不直接执行外部部署、数据库恢复或发送消息。内置演示数据及演示入口已移除,仅展示实际登记的记录。参考材料支持链接及文件附件,单文件 20 MB、每条需求最多 10 个;文件通过鉴权接口下载,随 SQLite 备份恢复。原托管站点不会被本次本地修改替换,其数据也不会自动迁入自建数据库。 + +域名切换记录:2026-09-16 已切换为 https://tap.zhongyuan.online,使用根路径,新证书已签发并配置续期重载。旧 /demands 地址只读跳转;账号与需求数据指纹校验一致,密码不变,新域名需要重新登录。 + + +2026-09-17 已将方案评审、文件附件及两轮审查修复部署至 https://tap.zhongyuan.online。服务器新镜像通过 129 项隔离接口检查及现有数据迁移演练;正式数据原表指纹一致,公网健康检查、登录资源和 20 MB 请求通道验证通过。部署与备份位置详见 DEPLOYED_TXY.md。 + +2026-09-17 已将模板预览、Word 下载、飞书模板总目录入口及两处审查修复部署至 https://tap.zhongyuan.online,版本 `20260917T063838Z-templates`。新镜像通过 142 项隔离接口检查,正式数据库各表指纹与最终切换前快照一致;公网功能脚本字节校验和访问检查通过,详见 DEPLOYED_TXY.md。 + + +## 管理员需求可见范围修复(2026-09-17 已上线) + +- 增加管理员「全部需求」入口,展示所有正式需求,并同步开放当前及历史评审附件的只读下载。 +- 列表和附件接口复用相同的读取条件,草稿与未保存附件仍仅本人可见;请求按当前账号角色鉴权。 +- 写入接口保留登记账号及指定开发责任人的校验,管理员观察权限不授予编辑、取消、变更、指派、代提方案或代做业务确认。 +- 「我的需求」、工作台计数和待办仅包含本人参与的需求;查看他人需求时显示只读提示。 +- 新增接口回归覆盖全部写操作拦截、当前/历史附件、草稿转正式、明确指派与撤销、角色降级即时失效等;共 174 项通过。多账号浏览器 5 组回归及 1440、390、320 像素布局验证通过,26 项单元测试、静态检查与生产构建通过。无需数据库迁移。 + +2026-09-17 已将管理员正式需求和附件只读查看功能部署至 https://tap.zhongyuan.online,版本 `20260917T071333Z-admin-visibility`。服务器镜像通过 174 项隔离接口检查,正式数据库各表指纹与切换前快照一致,公网访问及管理员页面脚本字节校验通过;部署与备份位置详见 DEPLOYED_TXY.md。 + + +## 完整交付流程(2026-09-17 已上线) + +- 方案确认后的交付计划由开发提出、业务确认,包含工作量、优先级、提测/验收反馈/上线日期及设计要求。需要设计时,完成独立设计确认后再开发。 +- 增加技术方案与依赖检查、开发进度、阻塞责任与跟进日期、协作记录;不跳过未确认计划、设计、阻塞和待处理变更。 +- 开发提交测试环境、版本、测试数据说明、自测、代码审查、集成证据和可编辑验收清单。业务逐项确认指定文档版本与测试轮次;不通过返回开发,超时不会自动通过。 +- 增加变更提出/撤回、开发影响评估和业务同意/拒绝。批准后同步范围、验收标准、文档版本及计划,并重新开发验收;拒绝保留原范围。新旧材料及确认均保留。 +- 增加缺陷登记、修复、独立复验与一般问题遗留申请。阻断缺陷必须复验关闭;一般遗留须业务确认计划。修复已交付版本会撤回旧提测状态,避免发布不含修复的旧版本。 +- 发布始终由当前开发责任人承担。发布前检查、验收版本匹配、备份/回滚/通知记录、生产验证、15 分钟至 7 天观察窗口以及交接/监控归档均有服务端条件检查。 +- 已上线或归档记录支持故障启动修复、实际回滚记录及复盘。涉及数据恢复前需业务明确批准目标版本和增量保留方案;在后续开发阶段仍能恢复上一线上版本。代码回滚不会擅自清除其他业务阻塞。 +- 允许业务方在交付期间更换开发账号,要求先处理待确认变更;旧方案与验收失效,新开发重新确认方案和计划,旧开发权限立即撤销。取消需求同步结束待确认变更及阻塞,过程历史保留。 +- 新增「交付流程」「缺陷」栏目,完善「需求变更」与历史逐项验收展示;页面按职责展示操作,保存后保留所在栏目,失败保留输入,离开前保护未保存内容。工作台提供按职责分配的待办与逾期提示。 +- 所有写入继续校验身份、业务/开发职责、状态、版本及数据库修订号;管理员只读权限不扩大。数据追加在需求 JSON 记录内,兼容历史需求,无需改变 SQLite 表结构;备份与恢复包含新记录。 +- 本次静态检查、TypeScript、生产构建及 34 项单元测试通过;原有 174 项接口回归、新增 102 项完整流程接口检查通过,覆盖多角色、并发冲突、退回、缺陷失效、时间门槛、恢复审批、交接、取消及重启持久化。 +- 新增 5 组完整流程页面回归通过:排期/设计/开发、手机提测/业务验收、发布验证/观察归档、变更/缺陷闭环、管理员只读;另有原模板容错 4 组和管理员权限 5 组浏览器回归通过。桌面及 390 像素手机截图已复核,无页面运行错误。 +- 完整交付流程与审查修复已部署为 `20260917T084659Z-full-workflow`,实际部署历史见 DEPLOYED_TXY.md。 + + +## 完整交付流程审查修复(2026-09-17 已上线) + +- 新发布前拦截所有未结束的数据恢复申请,开发可记录原因撤回,业务方可确认或退回。恢复操作和确认关联发布记录;旧版本遗留申请保留入口,但已被替代的申请不能再批准,只可撤回/退回后重新申请。 +- 设计确认待办覆盖已排期及开发中,校验当前方案版本;变更后旧设计不会再错误提示“开始开发”。历史设计明确标识,开发准入与提测继续使用相同确认条件。 +- 验收清单按现有编号集合生成未使用编号,删除中间项、手动调整编号后再添加不会产生系统生成的重复编号。 +- 新增受约束的紧急发布入口:仅当前开发责任人、已有线上故障、与原发布一致的方案和文档、业务规则/范围不变且无不可逆数据处理时可使用。自测、审查、构建回归、已知风险、备份恢复、通知和观察检查仍必填;未修复的阻断缺陷会拦截。其他情况继续常规评审验收。 +- 紧急发布保留实际版本及技术证据,撤回旧提测但不伪造验收通过记录;业务方收到关联发布版本及截止日期的补充验证待办,历史未补验记录也可处理。当前版本不通过返回修复;通过后仍须生产验证、观察、交接和缺陷处理完成才能归档。进度条使用“业务补验”,补验前不标记通过。 +- 单元测试 40 项、完整交付 HTTP 检查 123 项、原有接口回归 174 项通过;新增 4 组真实页面回归覆盖设计待办、清单增删、恢复撤回、手机紧急发布及业务补验归档,并检查管理员没有新增写入入口。桌面和手机截图复核通过。 +- 数据仍使用既有 SQLite 需求记录,无新表迁移;现有备份与恢复包含新增记录。本地及线上均已更新,线上版本为 `20260917T084659Z-full-workflow`。 + +2026-09-17 16:52(北京时间)已部署完整交付流程和四项审查修复至 https://tap.zhongyuan.online。新镜像通过全部 297 项隔离接口检查与现有数据副本演练,切换前后正式数据库各表指纹完全一致;公网健康、鉴权、静态资源及完整交付页面脚本字节验证通过。部署资料见 DEPLOYED_TXY.md。 diff --git a/README.md b/README.md index 3caca1b..b574374 100644 --- a/README.md +++ b/README.md @@ -1,126 +1,148 @@ -# 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 +需求登记账号管理业务信息并代表业务方确认方案;开发负责人默认由系统管理员担任,无需手动填写账号,负责从方案到发布的完整交付。管理员可只读查看全部正式需求及其附件,草稿与未保存附件仍仅本人可见;普通用户只可查看自己登记或被指定负责开发的需求。当前源代码已补齐排期、设计确认、开发、提测、验收、发布和归档,以及变更、缺陷、回滚与复盘。线上版本以 DEPLOYED_TXY.md 的部署记录为准。 -## 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 /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 ` or `--hostname ` 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 ` 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 ``. 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`,详见部署说明。 + +## 与已发布演示站的关系 + +此目录是独立服务器版本的源码。原 `chatgpt.site` 地址仍是原托管版本,本次修改不会替换它。自建版本不依赖该平台的登录、数据库或托管服务;原站的云端数据不会自动迁入自建数据库。 + +## 飞书登录与群通知 + +新增账号菜单入口「飞书绑定」,管理员另有「飞书集成」。在服务器配置飞书应用和群机器人后即可启用。新成员首次通过飞书授权后自动注册普通成员账号并进入工作台,无需预先开通或设置密码;重复登录复用账号。已有系统账号应先登录并绑定飞书以保留原有需求,不会按姓名或邮箱自动合并。飞书注册成员可选设置系统密码,解绑前需验证密码。 + +正式需求每次成功保存后推送流转摘要,草稿不通知。通知与需求一同持久化,后台每 3 秒处理一条,失败最多自动尝试 5 次;管理员可筛选失败通知、翻页查看全部历史记录(每页最多 50 条)、发送测试消息和重试失败通知。消息链接直接打开有权访问的需求详情。 + +配置步骤、权限、重试语义和上线检查见 [FEISHU.md](FEISHU.md)。 diff --git a/app/account/account.css b/app/account/account.css new file mode 100644 index 0000000..a319b02 --- /dev/null +++ b/app/account/account.css @@ -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}} diff --git a/app/account/feishu/page.tsx b/app/account/feishu/page.tsx new file mode 100644 index 0000000..71b9343 --- /dev/null +++ b/app/account/feishu/page.tsx @@ -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> }) { + const user = await requireUser('/account/feishu'); + const params = await searchParams; + const error = feishuErrorMessage(params.feishuError); + return
+
+

飞书绑定

+

当前账号:{user.displayName}({user.username})
绑定后可通过飞书登录,继续使用当前账号的需求和权限。

+ {error &&
{error}
} + {params.bound === '1' &&
飞书账号已绑定,下次可使用飞书登录。
} + +
返回工作台{user.role === 'admin' && 飞书集成管理}
+
+
; +} diff --git a/app/account/password/page.tsx b/app/account/password/page.tsx new file mode 100644 index 0000000..a0bb5df --- /dev/null +++ b/app/account/password/page.tsx @@ -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
+
需有序需求协作平台
+
+

{!passwordSet ? '设置系统密码' : user.mustChangePassword ? '设置你的密码' : '修改密码'}

+

当前账号:{user.username}

+ +
+
; +} diff --git a/app/admin/feishu/page.tsx b/app/admin/feishu/page.tsx new file mode 100644 index 0000000..e04ddcc --- /dev/null +++ b/app/admin/feishu/page.tsx @@ -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 ; +} diff --git a/app/admin/users/page.tsx b/app/admin/users/page.tsx new file mode 100644 index 0000000..3820c17 --- /dev/null +++ b/app/admin/users/page.tsx @@ -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 ; +} diff --git a/app/api/account/feishu/route.ts b/app/api/account/feishu/route.ts new file mode 100644 index 0000000..0bdad24 --- /dev/null +++ b/app/api/account/feishu/route.ts @@ -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); } +} diff --git a/app/api/admin/feishu/route.ts b/app/api/admin/feishu/route.ts new file mode 100644 index 0000000..23137e1 --- /dev/null +++ b/app/api/admin/feishu/route.ts @@ -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); } +} diff --git a/app/api/admin/users/route.ts b/app/api/admin/users/route.ts new file mode 100644 index 0000000..117df07 --- /dev/null +++ b/app/api/admin/users/route.ts @@ -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); } +} diff --git a/app/api/attachments/[id]/route.ts b/app/api/attachments/[id]/route.ts new file mode 100644 index 0000000..d6db2e6 --- /dev/null +++ b/app/api/attachments/[id]/route.ts @@ -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); } +} diff --git a/app/api/attachments/route.ts b/app/api/attachments/route.ts new file mode 100644 index 0000000..b3461de --- /dev/null +++ b/app/api/attachments/route.ts @@ -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); } +} diff --git a/app/api/auth/feishu/callback/route.ts b/app/api/auth/feishu/callback/route.ts new file mode 100644 index 0000000..90c8908 --- /dev/null +++ b/app/api/auth/feishu/callback/route.ts @@ -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 }); +} diff --git a/app/api/auth/feishu/start/route.ts b/app/api/auth/feishu/start/route.ts new file mode 100644 index 0000000..8abd6ba --- /dev/null +++ b/app/api/auth/feishu/start/route.ts @@ -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' } }); + } +} diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts new file mode 100644 index 0000000..3c10a68 --- /dev/null +++ b/app/api/auth/login/route.ts @@ -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); } +} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts new file mode 100644 index 0000000..e9e5b23 --- /dev/null +++ b/app/api/auth/logout/route.ts @@ -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); } +} diff --git a/app/api/auth/me/route.ts b/app/api/auth/me/route.ts new file mode 100644 index 0000000..f991811 --- /dev/null +++ b/app/api/auth/me/route.ts @@ -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); } +} diff --git a/app/api/auth/password/route.ts b/app/api/auth/password/route.ts new file mode 100644 index 0000000..ccaa462 --- /dev/null +++ b/app/api/auth/password/route.ts @@ -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); } +} diff --git a/app/api/demands/route.ts b/app/api/demands/route.ts index 1b9bfe8..01bf115 100644 --- a/app/api/demands/route.ts +++ b/app/api/demands/route.ts @@ -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.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); + 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=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);} } diff --git a/app/api/documents/[name]/route.ts b/app/api/documents/[name]/route.ts new file mode 100644 index 0000000..ae2085d --- /dev/null +++ b/app/api/documents/[name]/route.ts @@ -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'}});} +} diff --git a/app/api/health/route.ts b/app/api/health/route.ts new file mode 100644 index 0000000..89c880f --- /dev/null +++ b/app/api/health/route.ts @@ -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'}});} +} diff --git a/app/chatgpt-auth.ts b/app/chatgpt-auth.ts deleted file mode 100644 index a0ae2ed..0000000 --- a/app/chatgpt-auth.ts +++ /dev/null @@ -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 { - 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 { - 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; - } -} diff --git a/app/globals.css b/app/globals.css index e8a4729..1de26d9 100644 --- a/app/globals.css +++ b/app/globals.css @@ -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}.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;color:#7899cd;font-variant-numeric:tabular-nums}.guide-step h3{font-size:16px;margin-bottom:8px}.guide-step p{font-size:14px;color:#526887;line-height:1.9}.guide-step small{font-size:12px;color:#8a97aa;line-height:1.8;display:block;margin-top:8px}.guide-main>.info-banner{margin-top:25px}.guide-docs,.guide-rules{padding:22px;margin-bottom:20px}.guide-docs h2{display:flex;gap:8px;align-items:center;font-size:18px;margin-bottom:18px}.guide-docs a{display:flex;align-items:center;justify-content:space-between;padding:12px 0;text-decoration:none;color:#586c8a;font-size:14px;border-bottom:1px solid #edf1f6;gap:10px}.guide-docs a:hover{color:var(--blue)}.guide-docs a small{color:#97a7bf;padding-right:11px;font-size:12px}.guide-docs a:first-of-type{color:var(--blue)}.guide-docs a:last-child{border:0}.guide-rules h2{font-size:17px;margin-bottom:13px}.guide-rules p{font-size:13px;color:#617691;display:flex;align-items:flex-start;gap:9px;margin:16px 0}.guide-rules p svg{color:#809ecb;margin-top:3px}.guide-rules p:last-child{margin-bottom:0} +.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;color:#7899cd;font-variant-numeric:tabular-nums}.guide-step h3{font-size:16px;margin-bottom:8px}.guide-step p{font-size:14px;color:#526887;line-height:1.9}.guide-step small{font-size:12px;color:#8a97aa;line-height:1.8;display:block;margin-top:8px}.guide-main>.info-banner{margin-top:25px}.guide-docs,.guide-rules{padding:22px;margin-bottom:20px}.guide-docs h2{display:flex;gap:8px;align-items:center;font-size:18px;margin-bottom:18px}.guide-docs a{display:flex;align-items:center;justify-content:space-between;padding:12px 0;text-decoration:none;color:#586c8a;font-size:14px;border-bottom:1px solid #edf1f6;gap:10px}.guide-docs a:hover{color:var(--blue)}.guide-docs a small{color:#97a7bf;padding-right:11px;font-size:12px}.guide-docs a:first-of-type{color:var(--blue)}.guide-docs a:last-child{border:0}.guide-rules h2{font-size:17px;margin-bottom:13px}.guide-rules p{font-size:13px;color:#617691;display:flex;align-items:flex-start;gap:9px;margin:16px 0}.guide-rules p svg{color:#809ecb;margin-top:3px}.guide-rules p:last-child{margin-bottom:0} @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} diff --git a/app/layout.tsx b/app/layout.tsx index ab1293a..ffc4eef 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -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 {children}} diff --git a/app/login/page.tsx b/app/login/page.tsx new file mode 100644 index 0000000..2e14370 --- /dev/null +++ b/app/login/page.tsx @@ -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> }) { + 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
+
需有序需求协作平台
+
+

登录工作台

+

登记需求,跟进进度,让业务协作更有序。

+ {error &&
{error}
} + + {feishuEnabled &&
+ 或使用飞书 +
+ + +
+

首次飞书登录将自动注册普通成员账号。已有系统账号请先用密码登录并绑定飞书,以保留原有需求。

+
} +
+

{feishuEnabled ? '支持管理员开通的账号,或通过飞书首次登录自动注册。' : '使用本系统账号登录,账号由管理员统一开通。'}

+
; +} diff --git a/app/page.tsx b/app/page.tsx index 56f1be9..bd620de 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,4 +1,11 @@ import DemandApp from '@/components/demand/app'; -import { requireChatGPTUser } from './chatgpt-auth'; -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 } +import { hasAccountPassword, requireUser } from '@/lib/server/auth'; +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; +export default async function Page({ searchParams }: { searchParams: Promise> }) { + 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 ; +} diff --git a/build/sites-vite-plugin.LICENSE b/build/sites-vite-plugin.LICENSE deleted file mode 100644 index 4243cb4..0000000 --- a/build/sites-vite-plugin.LICENSE +++ /dev/null @@ -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. diff --git a/build/sites-vite-plugin.ts b/build/sites-vite-plugin.ts deleted file mode 100644 index 2ece1b9..0000000 --- a/build/sites-vite-plugin.ts +++ /dev/null @@ -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 { - 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 "/"; - } -} diff --git a/cloudflare-env.d.ts b/cloudflare-env.d.ts deleted file mode 100644 index 856e090..0000000 --- a/cloudflare-env.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare namespace Cloudflare { - interface Env { - DB?: D1Database; - BUCKET?: R2Bucket; - } -} diff --git a/components/account/feishu-account.tsx b/components/account/feishu-account.tsx new file mode 100644 index 0000000..7473a8e --- /dev/null +++ b/components/account/feishu-account.tsx @@ -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) { + 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
+ {error &&
{error}
} + {success &&
{success}
} + {binding ? <> +

已绑定:{binding.name}

+ {!passwordSet ? <> +

当前账号通过飞书注册,尚未设置系统密码。请先设置密码,再解除绑定。

+ 设置系统密码 + : <> +

解除绑定需验证系统密码,其他设备需重新登录。解绑后此飞书身份再次登录会创建新账号;原需求仍可通过当前账号密码访问。

+
+
+
+
+ } + : configured ?
+ +
:

飞书登录尚未配置,请联系管理员完成飞书应用设置。

} +
; +} diff --git a/components/account/feishu-management.tsx b/components/account/feishu-management.tsx new file mode 100644 index 0000000..35d58fe --- /dev/null +++ b/components/account/feishu-management.tsx @@ -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>([null]); + async function request(action?: 'test' | 'retry', id?: string, selection?: { filter: FeishuDeliveryFilter; cursors: Array }) { + 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
+
返回工作台需有序
+
+

飞书集成

管理飞书登录与需求流转群通知。

+ {error &&
{error}
} + {message &&
{message}
} + {status.configurationError &&
{status.configurationError}
} +
+

飞书登录 {status.loginConfigured ? '已配置' : '未配置'}

+

首次飞书登录自动创建普通成员账号,直接进入工作台;已有绑定继续使用原账号的角色和需求。

+
授权回调地址
{status.callbackUrl}
企业限制
{status.tenantRestricted ? '已限制为指定企业' : '按飞书应用可用范围注册及登录'}
+ 绑定我的飞书账号 +
+

群机器人 {status.botConfigured ? '已配置' : '未配置'}

+

正式需求每次成功保存后发送流转摘要,包含标题、状态、操作人和详情链接。草稿不推送。

+

签名校验:{status.botSigned ? '已配置' : '未配置'}

+ +
+
+
配置步骤与通知范围 +
  1. 在飞书开放平台创建企业自建应用,配置网页应用能力,将上方回调地址加入安全设置的重定向 URL,发布应用并设置成员可用范围。
  2. +
  3. 在服务器环境变量配置 FEISHU_APP_ID、FEISHU_APP_SECRET,可用 FEISHU_TENANT_KEY 限定企业。
  4. +
  5. 在目标群添加自定义机器人,配置 FEISHU_BOT_WEBHOOK;开启签名校验时同时配置 FEISHU_BOT_SECRET。关键词校验可填写「需有序」。
  6. +
  7. 重启服务后刷新状态,发送测试消息。密钥仅在服务器设置,无需填写到浏览器。
+

群成员均可看到通知摘要,请选择适合接收全部正式需求摘要的群。查看详情仍需系统登录及对应权限。发送失败自动重试最多 5 次,之后可手动重试;网络超时可能导致重复消息,可按需求编号和保存版本核对。

+
+
+

通知记录

+ {status.deliveries.length ?
+ {status.deliveries.map(item => )}
需求 / 保存版本发送状态尝试次数创建时间操作
{item.demandId}第 {item.revision} 次保存{deliveryLabels[item.status]}{item.lastError && {item.lastError}}{item.attempts}{date(item.createdAt)}{item.status === 'failed' ? : '—'}
+ :

{status.deliveryFilter === 'failed' ? '当前页暂无失败通知。可返回上一页或切换为全部通知。' : pageCursors.length > 1 ? '当前页暂无通知,请返回上一页。' : '暂无通知。配置机器人后,新登记及后续流转的正式需求会显示在这里。'}

} +
第 {pageCursors.length} 页 · 每页最多 50 条{status.failedCount > 0 ? ` · 共有 ${status.failedCount} 条失败通知` : ''}
+
+
+
; +} diff --git a/components/account/login-form.tsx b/components/account/login-form.tsx new file mode 100644 index 0000000..def0636 --- /dev/null +++ b/components/account/login-form.tsx @@ -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) { + 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
+ {error &&
{error}
} +
+ + +
+ + +
+ +
+

需要开通账号或忘记密码,请联系系统管理员。

+
; +} diff --git a/components/account/password-form.tsx b/components/account/password-form.tsx new file mode 100644 index 0000000..5fa69c1 --- /dev/null +++ b/components/account/password-form.tsx @@ -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) { + event.preventDefault(); + const fields = new FormData(event.currentTarget); + setError(''); + if (fields.get('newPassword') !== fields.get('confirmation')) { + setError('两次输入的新密码不一致,请重新确认。'); + event.currentTarget.querySelector('#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 &&
你当前通过飞书登录。设置系统密码后,也可使用上方账号和密码登录。
} + {mustChangePassword &&
请将管理员分配的临时密码改为自己的密码,完成后即可进入工作台。
} +
+ + {error &&
{error}
} +
+ {passwordSet && } +
+ + 12–128 个字符,可使用方便记忆的长密码。 +
+ + + +
+
+
+ {!mustChangePassword && 返回工作台} + +
+ ; +} diff --git a/components/account/user-management.tsx b/components/account/user-management.tsx new file mode 100644 index 0000000..69bf66a --- /dev/null +++ b/components/account/user-management.tsx @@ -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) { + 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 { if (!open && !busy) onClose(); }}> + { if (busy) event.preventDefault(); }} onPointerDownOutside={event => { if (busy) event.preventDefault(); }}> +
{title}
+ {creating ? '为指定用户创建账号,首次登录后由用户设置自己的密码。' : action.kind === 'reset-password' ? `为 ${action.user.displayName}(${action.user.username})设置新的临时密码,原有登录将失效。` : action.kind === 'disable' ? `停用后,${action.user.displayName} 将退出登录且无法再次登录。已登记的需求会保留。` : `启用后,${action.user.displayName} 可继续使用原账号和密码登录。`} +
+ {error &&
{error}
} +
+ {creating && <> + + + + } + {settingPassword && <> + +
+ + +
+ 12–128 个字符。请保存并告知用户,关闭后无法查看。 + } +
+
+
+
+
; +} + +export function UserManagement({ currentUserId }: { currentUserId: string }) { + const [users, setUsers] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [query, setQuery] = useState(''); + const [action, setAction] = useState(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
+
返回工作台
需有序
+
+

账号管理

为指定用户开通访问权限,统一管理账号状态。

+

仅已开通且处于启用状态的账号可以登录。每位用户只能查看和管理自己登记的需求。

+ {message &&
{message}
} + {error &&
{error}
} +
+

全部账号

{users.length}
+
+ {matching.map(user => )} +
用户角色状态最近登录操作
{user.displayName}{user.userId === currentUserId && 我}{user.username}
{user.role === 'admin' ? '管理员' : '业务用户'}{user.disabled ? '已停用' : '已启用'}{user.mustChangePassword && !user.disabled && 待设置密码}{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 }) : '尚未登录'}
{user.userId === currentUserId ? 修改密码 : <>}
+ {loading && users.length === 0 &&

正在加载账号…

} + {!loading && !matching.length &&

{query ? '没有找到匹配的账号' : error ? '账号列表暂不可用' : '暂无账号'}

{query ? '试试其他账号或姓名。' : error ? '请重新加载后再试。' : '点击“开通账号”为指定用户添加访问权限。'}

} +
{search ? `找到 ${matching.length} 个账号` : `共 ${users.length} 个账号,${users.filter(user => !user.disabled).length} 个已启用`}停用账号会保留已登记的需求
+
+
+ {action && setAction(null)} onSaved={saved} />} +
; +} diff --git a/components/demand/app.tsx b/components/demand/app.tsx index 40844b8..5feaa63 100644 --- a/components/demand/app.tsx +++ b/components/demand/app.tsx @@ -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([]);const [examples,setExamples]=useState(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(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([]);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(null);const [form,setForm]=useState<{initial?:Demand}|null>(null);const [dashboardKey,setDashboardKey]=useState(0); + const [detailTab,setDetailTab]=useState(); + 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(null); + const writeVersion=useRef(0);const savedWrites=useRef(new Map()); + 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}}).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}}).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
{loading&&
}
工作空间{view}{today}
- {loadError&&
{loadError}{demo?' 当前展示示例数据。':''}
} - {view==='流程与规范'?:{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
{loading&&
}
工作空间{view}
+ {loadError&&
{loadError}
} + {view==='流程与规范'?:{setSelected(d);setDetailTab(undefined);setActionError('')}} onNew={startNew} onGuide={()=>navigate('流程与规范')} onRefresh={reload} loading={loading} unavailable={Boolean(loadError)}/>}
- {selected&&!form&&setSelected(null)} onEdit={d=>{setForm({initial:d});setActionError('')}} onAction={action} busy={busy} error={actionError}/>} - {form&&{try{await save(body)}catch{}}} onClose={()=>setForm(null)} busy={busy} error={actionError} userName={userName==='seedy@sites.test'?'业务用户':userName} existing={actual}/>} + {selected&&!form&&setSelected(null)} onEdit={d=>{setForm({initial:d});setActionError('')}} onAction={action} busy={busy} error={actionError}/>} + {form&&{try{await save(body)}catch{}}} onClose={()=>setForm(null)} busy={busy} error={actionError} userName={userName} existing={personalDemands.filter(d=>d.access?.business??true)}/>} {toast&&
{toast}
}
; } diff --git a/components/demand/attachments.tsx b/components/demand/attachments.tsx new file mode 100644 index 0000000..cd74e7d --- /dev/null +++ b/components/demand/attachments.tsx @@ -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

暂无附件

; + return
    {files.map(file =>
  • +
  • )}
; +} + +export function AttachmentPicker({ files, onChange, disabled, uploading, onUploadingChange, onNewUpload, inputRef, compact = false }: { + inputRef?: RefObject; compact?: boolean; + files: Attachment[]; onChange: (files: Attachment[]) => void; disabled: boolean; uploading: boolean; + onUploadingChange: (busy: boolean) => void; onNewUpload: (file: Attachment) => void; +}) { + const localInput = useRef(null); + const input = inputRef ?? localInput; + const inFlight = useRef(false); + const [errors, setErrors] = useState([]); + const [progress, setProgress] = useState(''); + const [recoverable, setRecoverable] = useState([]); + const [recoveryLoading, setRecoveryLoading] = useState(true); + const [recoveryError, setRecoveryError] = useState(''); + const [recoveryOpen, setRecoveryOpen] = useState(false); + const recoveryRequest = useRef(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
+ {!compact &&
文件附件{files.length}/{MAX_ATTACHMENTS}
} +

可上传文档、图片等参考材料,每个文件不超过 20 MB,最多 10 个。保存需求后生效。

+ { const selected = Array.from(event.currentTarget.files ?? []); event.currentTarget.value = ''; void upload(selected); }}/> + {!compact && } + {progress &&

{progress}

} + {errors.length > 0 &&
    {errors.map((message, index) =>
  • {message}
  • )}
} + {files.length > 0 &&
    {files.map(file =>
  • +
  • )}
} +
+ {recoveryLoading ?

正在读取未保存附件…

: recoveryError ?
未保存附件列表加载失败:{recoveryError}
: } +
+ {available.length > 0 &&
setRecoveryOpen(event.currentTarget.open)}>找回未保存的附件({available.length})

此前已上传但尚未保存到需求的文件,24 小时内可选用。选用后移除或取消编辑会保留原文件;“清理”会删除文件,请核对其他窗口是否仍在使用。

    {available.map(file =>
  • {file.name}{formatFileSize(file.size)}
  • )}
} +

{compact ? '文档链接可在下方填写。' : '链接可继续填写在上方。'}修改已有附件后需保存;历史评审引用的文件仍会保留。

+
; +} diff --git a/components/demand/dashboard.tsx b/components/demand/dashboard.tsx index b5dcf9e..65b4792 100644 --- a/components/demand/dashboard.tsx +++ b/components/demand/dashboard.tsx @@ -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 {d.status}} -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 <> -

{view}

{view==='我的工作台'?'一起让每一个好需求,有序落地。':view==='草稿箱'?'还没写完的想法,在这里继续。':view==='待我处理'?'补齐业务信息、确认结果,让需求继续向前。':'从业务诉求到交付完成,进展都在这里。'}

- {view==='我的工作台'&&<>
{[['我的需求',submitted.length,'我的需求'],['进行中',inProgress.length,'进行中'],['待我处理',todos.length,'待我处理'],['已完成',completed.length,'已完成']].map(([label,value,to])=>)}
待办提醒{todos.length?`你有 ${todos.filter(d=>d.status==='待评审').length} 项需求待补充,${todos.filter(d=>d.status==='待验收').length} 项待验收`:'当前没有待办,需求进展尽在掌握。'}
} -

{view==='我的工作台'?'最近需求':view==='待我处理'?'需要你处理':view==='草稿箱'?'未提交的草稿':'需求列表'}

{view==='我的工作台'?:{filtered.length} 条需求}
- {view!=='草稿箱'&&
{['全部需求','进行中','待验收','已完成'].map(t=>)}
} +

{view}

{view==='我的工作台'?'一起让每一个好需求,有序落地。':view==='全部需求'?'查看所有已登记需求、评审进展与附件;个人草稿仅本人可见。':view==='草稿箱'?'还没写完的想法,在这里继续。':view==='待我处理'?'补齐业务信息、确认结果,让需求继续向前。':'从业务诉求到交付完成,进展都在这里。'}

+ {view==='我的工作台'&&<>
{[['我的需求',submitted.length,'我的需求'],['进行中',inProgress.length,'进行中'],['待我处理',todos.length,'待我处理'],['已完成',completed.length,'已完成']].map(([label,value,to])=>)}
待办提醒{pending?(loading?'正在加载待办…':'待办信息暂不可用'):todos.length?`你有 ${todos.length} 项待办${todos.some(d=>dueDate(d)&&dueDate(d)!
} +

{view==='我的工作台'?'最近需求':view==='待我处理'?'需要你处理':view==='草稿箱'?'未提交的草稿':'需求列表'}

{view==='我的工作台'?:{pending?'—':filtered.length} 条需求}
+ {view!=='草稿箱'&&
{['全部需求','待评审','已排期','进行中','待验收','待发布','已上线','已完成','已取消'].map(t=>)}
}
{filterOpen&&
} -
{rows.map(d=>)}
需求名称状态优先级期望上线
{d.id}·{d.fields.department||'未填写部门'}
{d.status==='待评审'&&!d.reviewReady&&资料待补充}{d.blocked&&阻塞}{d.fields.priority} {d.fields.priority==='P0'?'紧急':d.fields.priority==='P1'?'高':'普通'}{d.fields.noFixedDate?'无固定日期':d.fields.expectedDate?d.fields.expectedDate.slice(5):'待填写'}
- {!rows.length&&
{query?:}

{query||priority!=='全部优先级'?'没有匹配的需求':view==='待我处理'?'所有待办都处理好了':view==='草稿箱'?'还没有草稿':'从第一个需求开始'}

{query?'试试其他关键词或调整筛选条件。':'把业务问题写下来,让每一步都有据可循。'}

} +
{rows.map(d=>)}
需求名称状态优先级期望上线
{d.id}·{d.fields.department||'未填写部门'}{view==='全部需求'&&<>·负责人:{d.fields.owner||'待补充'}}{d.access?.developer&&<>·我负责开发}
{(workflowTask(d)||d.status==='待评审')&&{workflowTask(d)||reviewStage(d)}}{dueDate(d)&&dueDate(d)!已逾期 · {dueDate(d)}}{d.blocked&&阻塞}{d.fields.priority} {d.fields.priority==='P0'?'紧急':d.fields.priority==='P1'?'高':'普通'}{d.fields.noFixedDate?'无固定日期':d.fields.expectedDate?d.fields.expectedDate.slice(5):'待填写'}
+ {!rows.length&&pending&&

{loading?'正在加载需求…':'暂时无法加载需求'}

{!loading&&

请使用上方的“重新加载”按钮重试。

}
} + {!rows.length&&!pending&&
{query?:}

{query||priority!=='全部优先级'?'没有匹配的需求':view==='待我处理'?'所有待办都处理好了':view==='草稿箱'?'还没有草稿':view==='全部需求'?'暂时没有正式需求':'从第一个需求开始'}

{query?'试试其他关键词或调整筛选条件。':'把业务问题写下来,让每一步都有据可循。'}

} {view!=='我的工作台'&&rows.length>0&&
共 {rows.length} 条,已显示全部结果
}
{view==='我的工作台'&&}
-
{demo?'当前展示示例数据,登记后将进入你的工作空间。':'期望上线为业务期望,正式交付时间以评审计划为准。'}
+
期望上线为业务期望,正式交付时间以评审计划为准。
; } diff --git a/components/demand/detail.tsx b/components/demand/detail.tsx index eddbc04..d7ac207 100644 --- a/components/demand/detail.tsx +++ b/components/demand/detail.tsx @@ -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
{label}

{value||'待补充'}

} -export function DemandDetail({d,onClose,onEdit,onAction,busy,error}:{d:Demand;onClose:()=>void;onEdit:(d:Demand)=>void;onAction:(body:SaveInput)=>Promise;busy:boolean;error:string}){ - const [tab,setTab]=useState('需求详情');const [mode,setMode]=useState('');const [content,setContent]=useState('');const [reason,setReason]=useState('');const [results,setResults]=useState(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;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(d.acceptance?.items.map(()=> '待测')??[]);const [notes,setNotes]=useState('');const [confirm,setConfirm]=useState(false);const [localError,setLocalError]=useState(''); + const errorRef=useRef(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 {if(!open&&!mode&&!busy)onClose()}}>{if(mode)e.preventDefault()}}>
{d.id}{d.demo&&示例}
{f.title}{f.project} / {f.module} ·{f.department} ·负责人:{f.owner}
-
{statuses.map((s,i)=>
{i:i+1}{s}
)}
-
{['需求详情','进度记录','需求变更','业务验收'].map(t=>)}
+ return <>{if(!open&&!busy)requestLeave()}}>{if(mode||reviewDirty)e.preventDefault()}}>
{d.id}
{f.title}{f.project} / {f.module} ·{f.department} ·负责人:{f.owner}
+
{statuses.map((s,i)=>{const done=i{done?:i+1}{emergency&&s==='待验收'?'业务补验':emergency&&s==='待发布'?'紧急发布':s}
})}
+
{['需求详情','需求评审','交付流程','业务验收','缺陷','需求变更','进度记录'].map(t=>)}
- {(error||localError)&&
{error||localError}
} - {d.demo&&
当前为示例需求,验收和变更操作只用于体验,不影响实际业务数据。
} - {mode==='change'||mode==='cancel'?

{mode==='change'?'提出需求变更':'确认取消需求'}

{mode==='change'?'记录希望调整的内容,开发负责人评估影响、双方确认后,再更新范围与计划。':'取消后会保留需求及过程记录。请填写明确的业务原因。'}

{mode==='change'&&