From 2149aeb6ede4711fe6ded544e6d683825e0b5541 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 16 Sep 2026 14:46:32 +0800 Subject: [PATCH] Build business demand registration workspace from SOP --- .gitignore | 48 + .npmrc | 3 + .openai/hosting.json | 5 + IMPLEMENTATION.md | 24 + README.md | 126 + app/api/demands/route.ts | 50 + app/chatgpt-auth.ts | 90 + app/globals.css | 19 + app/layout.tsx | 4 + app/page.tsx | 4 + build/sites-vite-plugin.LICENSE | 21 + build/sites-vite-plugin.ts | 230 + cloudflare-env.d.ts | 6 + components.json | 21 + components/demand/app.tsx | 36 + components/demand/dashboard.tsx | 25 + components/demand/detail.tsx | 38 + components/demand/form.tsx | 54 + components/demand/guide.tsx | 10 + components/ui/accordion.tsx | 66 + components/ui/alert-dialog.tsx | 196 + components/ui/alert.tsx | 66 + components/ui/aspect-ratio.tsx | 11 + components/ui/attachment.tsx | 204 + components/ui/avatar.tsx | 109 + components/ui/badge.tsx | 48 + components/ui/breadcrumb.tsx | 109 + components/ui/bubble.tsx | 125 + components/ui/button-group.tsx | 83 + components/ui/button.tsx | 64 + components/ui/calendar.tsx | 220 + components/ui/card.tsx | 92 + components/ui/carousel.tsx | 241 + components/ui/chart.tsx | 377 + components/ui/checkbox.tsx | 32 + components/ui/collapsible.tsx | 33 + components/ui/combobox.tsx | 310 + components/ui/command.tsx | 184 + components/ui/context-menu.tsx | 252 + components/ui/dialog.tsx | 158 + components/ui/direction.tsx | 22 + components/ui/drawer.tsx | 135 + components/ui/dropdown-menu.tsx | 257 + components/ui/empty.tsx | 104 + components/ui/field.tsx | 248 + components/ui/form.tsx | 167 + components/ui/hover-card.tsx | 44 + components/ui/input-group.tsx | 170 + components/ui/input-otp.tsx | 77 + components/ui/input.tsx | 21 + components/ui/item.tsx | 193 + components/ui/kbd.tsx | 28 + components/ui/label.tsx | 24 + components/ui/marker.tsx | 69 + components/ui/menubar.tsx | 276 + components/ui/message-scroller.tsx | 130 + components/ui/message.tsx | 92 + components/ui/native-select.tsx | 62 + components/ui/navigation-menu.tsx | 168 + components/ui/pagination.tsx | 127 + components/ui/popover.tsx | 89 + components/ui/progress.tsx | 32 + components/ui/radio-group.tsx | 45 + components/ui/resizable.tsx | 53 + components/ui/scroll-area.tsx | 58 + components/ui/select.tsx | 190 + components/ui/separator.tsx | 28 + components/ui/sheet.tsx | 143 + components/ui/sidebar.tsx | 723 + components/ui/skeleton.tsx | 13 + components/ui/slider.tsx | 63 + components/ui/sonner.tsx | 40 + components/ui/spinner.tsx | 16 + components/ui/switch.tsx | 35 + components/ui/table.tsx | 116 + components/ui/tabs.tsx | 91 + components/ui/textarea.tsx | 18 + components/ui/toggle-group.tsx | 83 + components/ui/toggle.tsx | 47 + components/ui/tooltip.tsx | 57 + db/index.ts | 13 + db/schema.ts | 5 + drizzle.config.ts | 7 + drizzle/0000_curvy_paibok.sql | 9 + drizzle/meta/0000_snapshot.json | 73 + drizzle/meta/_journal.json | 13 + eslint.config.mjs | 28 + examples/d1/app/api/notes/route.ts | 58 + examples/d1/db/schema.ts | 9 + hooks/use-mobile.ts | 19 + lib/demand.ts | 21 + lib/demo.ts | 11 + lib/utils.ts | 6 + next.config.ts | 7 + package-lock.json | 14424 ++++++++++++++++ package.json | 68 + postcss.config.mjs | 7 + public/docs/开发SOP_公示版.md | 463 + .../docs/开发SOP附件/附件01_需求登记模板.md | 38 + .../docs/开发SOP附件/附件02_需求文档模板.md | 77 + .../开发SOP附件/附件03_数据来源填写模板.md | 24 + .../docs/开发SOP附件/附件04_验收记录模板.md | 11 + .../开发SOP附件/附件05_需求变更记录模板.md | 5 + .../docs/开发SOP附件/附件06_缺陷记录模板.md | 16 + .../docs/开发SOP附件/附件07_发布记录模板.md | 12 + public/docs/附件01_需求登记模板.md | 38 + public/docs/附件02_需求文档模板.md | 77 + public/docs/附件03_数据来源填写模板.md | 24 + public/docs/附件04_验收记录模板.md | 11 + public/docs/附件05_需求变更记录模板.md | 5 + public/docs/附件06_缺陷记录模板.md | 16 + public/docs/附件07_发布记录模板.md | 12 + public/favicon.svg | 1 + scripts/build-verified.sh | 26 + scripts/execution-profile.mjs | 16 + scripts/install-ci.mjs | 51 + scripts/install-ci.sh | 211 + scripts/install-pnpm.sh | 216 + scripts/pnpm-install.mjs | 261 + scripts/run-framework.mjs | 23 + scripts/sites-env.mjs | 22 + scripts/sites-env.sh | 52 + tsconfig.json | 47 + vendor/shadcn-tailwind-4.13.0.LICENSE.md | 21 + vendor/shadcn-tailwind-4.13.0.css | 629 + vite.config.ts | 68 + 126 files changed, 25399 insertions(+) create mode 100644 .gitignore create mode 100644 .npmrc create mode 100644 .openai/hosting.json create mode 100644 IMPLEMENTATION.md create mode 100644 README.md create mode 100644 app/api/demands/route.ts create mode 100644 app/chatgpt-auth.ts create mode 100644 app/globals.css create mode 100644 app/layout.tsx create mode 100644 app/page.tsx create mode 100644 build/sites-vite-plugin.LICENSE create mode 100644 build/sites-vite-plugin.ts create mode 100644 cloudflare-env.d.ts create mode 100644 components.json create mode 100644 components/demand/app.tsx create mode 100644 components/demand/dashboard.tsx create mode 100644 components/demand/detail.tsx create mode 100644 components/demand/form.tsx create mode 100644 components/demand/guide.tsx create mode 100644 components/ui/accordion.tsx create mode 100644 components/ui/alert-dialog.tsx create mode 100644 components/ui/alert.tsx create mode 100644 components/ui/aspect-ratio.tsx create mode 100644 components/ui/attachment.tsx create mode 100644 components/ui/avatar.tsx create mode 100644 components/ui/badge.tsx create mode 100644 components/ui/breadcrumb.tsx create mode 100644 components/ui/bubble.tsx create mode 100644 components/ui/button-group.tsx create mode 100644 components/ui/button.tsx create mode 100644 components/ui/calendar.tsx create mode 100644 components/ui/card.tsx create mode 100644 components/ui/carousel.tsx create mode 100644 components/ui/chart.tsx create mode 100644 components/ui/checkbox.tsx create mode 100644 components/ui/collapsible.tsx create mode 100644 components/ui/combobox.tsx create mode 100644 components/ui/command.tsx create mode 100644 components/ui/context-menu.tsx create mode 100644 components/ui/dialog.tsx create mode 100644 components/ui/direction.tsx create mode 100644 components/ui/drawer.tsx create mode 100644 components/ui/dropdown-menu.tsx create mode 100644 components/ui/empty.tsx create mode 100644 components/ui/field.tsx create mode 100644 components/ui/form.tsx create mode 100644 components/ui/hover-card.tsx create mode 100644 components/ui/input-group.tsx create mode 100644 components/ui/input-otp.tsx create mode 100644 components/ui/input.tsx create mode 100644 components/ui/item.tsx create mode 100644 components/ui/kbd.tsx create mode 100644 components/ui/label.tsx create mode 100644 components/ui/marker.tsx create mode 100644 components/ui/menubar.tsx create mode 100644 components/ui/message-scroller.tsx create mode 100644 components/ui/message.tsx create mode 100644 components/ui/native-select.tsx create mode 100644 components/ui/navigation-menu.tsx create mode 100644 components/ui/pagination.tsx create mode 100644 components/ui/popover.tsx create mode 100644 components/ui/progress.tsx create mode 100644 components/ui/radio-group.tsx create mode 100644 components/ui/resizable.tsx create mode 100644 components/ui/scroll-area.tsx create mode 100644 components/ui/select.tsx create mode 100644 components/ui/separator.tsx create mode 100644 components/ui/sheet.tsx create mode 100644 components/ui/sidebar.tsx create mode 100644 components/ui/skeleton.tsx create mode 100644 components/ui/slider.tsx create mode 100644 components/ui/sonner.tsx create mode 100644 components/ui/spinner.tsx create mode 100644 components/ui/switch.tsx create mode 100644 components/ui/table.tsx create mode 100644 components/ui/tabs.tsx create mode 100644 components/ui/textarea.tsx create mode 100644 components/ui/toggle-group.tsx create mode 100644 components/ui/toggle.tsx create mode 100644 components/ui/tooltip.tsx create mode 100644 db/index.ts create mode 100644 db/schema.ts create mode 100644 drizzle.config.ts create mode 100644 drizzle/0000_curvy_paibok.sql create mode 100644 drizzle/meta/0000_snapshot.json create mode 100644 drizzle/meta/_journal.json create mode 100644 eslint.config.mjs create mode 100644 examples/d1/app/api/notes/route.ts create mode 100644 examples/d1/db/schema.ts create mode 100644 hooks/use-mobile.ts create mode 100644 lib/demand.ts create mode 100644 lib/demo.ts create mode 100644 lib/utils.ts create mode 100644 next.config.ts create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 postcss.config.mjs create mode 100644 public/docs/开发SOP_公示版.md create mode 100644 public/docs/开发SOP附件/附件01_需求登记模板.md create mode 100644 public/docs/开发SOP附件/附件02_需求文档模板.md create mode 100644 public/docs/开发SOP附件/附件03_数据来源填写模板.md create mode 100644 public/docs/开发SOP附件/附件04_验收记录模板.md create mode 100644 public/docs/开发SOP附件/附件05_需求变更记录模板.md create mode 100644 public/docs/开发SOP附件/附件06_缺陷记录模板.md create mode 100644 public/docs/开发SOP附件/附件07_发布记录模板.md create mode 100644 public/docs/附件01_需求登记模板.md create mode 100644 public/docs/附件02_需求文档模板.md create mode 100644 public/docs/附件03_数据来源填写模板.md create mode 100644 public/docs/附件04_验收记录模板.md create mode 100644 public/docs/附件05_需求变更记录模板.md create mode 100644 public/docs/附件06_缺陷记录模板.md create mode 100644 public/docs/附件07_发布记录模板.md create mode 100644 public/favicon.svg create mode 100755 scripts/build-verified.sh create mode 100644 scripts/execution-profile.mjs create mode 100644 scripts/install-ci.mjs create mode 100755 scripts/install-ci.sh create mode 100755 scripts/install-pnpm.sh create mode 100644 scripts/pnpm-install.mjs create mode 100644 scripts/run-framework.mjs create mode 100644 scripts/sites-env.mjs create mode 100755 scripts/sites-env.sh create mode 100644 tsconfig.json create mode 100644 vendor/shadcn-tailwind-4.13.0.LICENSE.md create mode 100644 vendor/shadcn-tailwind-4.13.0.css create mode 100644 vite.config.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f94cfad --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/.vinext/ +/out/ + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +next-env.d.ts +/dist/ +/.wrangler/ +# Checkout-local execution profile and tool state; never publish them. +/.sites-runtime/ +/.agents/ +/.codex/ +/outputs/ +/work/ + +*.tsbuildinfo diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..9f274d6 --- /dev/null +++ b/.npmrc @@ -0,0 +1,3 @@ +audit=false +fund=false +update-notifier=false diff --git a/.openai/hosting.json b/.openai/hosting.json new file mode 100644 index 0000000..dad4130 --- /dev/null +++ b/.openai/hosting.json @@ -0,0 +1,5 @@ +{ + "d1": "DB", + "r2": null, + "project_id": "appgprj_6aaa34146070819195304ffeb50f65a8" +} diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md new file mode 100644 index 0000000..d5a0191 --- /dev/null +++ b/IMPLEMENTATION.md @@ -0,0 +1,24 @@ +# 需有序 · 业务需求登记管理 + +基于本目录《开发SOP_公示版》及附件01–07制作,原文件保持不变。 + +## 已实现 +- 我的工作台、需求列表、检索与优先级/项目筛选、待办、草稿。 +- 四步登记表;草稿、基本登记和提交评审分别校验。 +- 需求详情、版本冲突保护、同名需求提示/拦截。 +- 业务验收清单和确认留痕;通过转待发布,不通过退回开发中。 +- 已确认需求提出变更;保留原字段快照,等待开发评估及双方确认。 +- 取消需求留痕、记录导出、原SOP和7个模板下载。 +- 通过平台登录;按实际登录账号隔离D1持久化记录。 +- 示例数据只用于页面体验,不会存入正式数据库。 + +## 当前使用边界 +这是业务端首版,站点默认仅创建者可访问。表单中的“需求负责人”是业务联系人,不表示已向该人员授权、指派系统任务或发送通知。跨部门成员权限、评审排期/开发提测/发布管理后台与企业账号集成尚未配置。实际登记后可维护信息并提交评审;后续阶段需要组织的开发协作系统接入,当前仅在明确标注的示例中体验。参考材料通过共享链接关联,目前未提供文件上传。 + +## 数据与运行 +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 普通”避免误解;其余文案随实际数据动态更新。 + +验证记录:TypeScript 检查通过;完整构建通过;本地接口20项检查覆盖未登录、归属隔离、分阶段校验、持久化、去重、版本冲突、验收版本/清单/显式确认、通过与退回、变更快照。通过内置浏览器完成保存草稿→刷新→继续填写→正式登记、示例逐项验收、未保存关闭提示;检查1536×1024与390×844,无页面横向溢出,手机表格可独立横向滚动。WebMCP已验证搜索的有效/无效输入以及打开登记表;不会自动提交需求。测试数据仅写入本地库并已清理,生产库不预置测试数据。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..3caca1b --- /dev/null +++ b/README.md @@ -0,0 +1,126 @@ +# vinext-starter + +A clean full-stack starter running on [vinext](https://github.com/cloudflare/vinext), with optional Cloudflare D1 and Drizzle support. + +## Prerequisites + +- Node.js `>=22.13.0` +- Portable: Windows, macOS, or Linux; no Bash required +- Managed Linux: managed Linux runtime with Bash, `flock`, `curl`, `sha256sum`, and GNU `timeout` +- Git is required only for publishing + +## Sites Lifecycle + +The Sites initializer copies the shared starter and selects managed-linux only when `SITES_MANAGED_LINUX_CONTAINER=1`; otherwise it selects portable. It saves the selection only in ignored `.sites-runtime/execution-profile.json`. Both profiles copy/configure first, then use the plugin's separate `install-dependencies.mjs` step to measure installation independently. Edit source under `app/` and follow the Sites skill for installation, preview, builds, and publishing. + +Whenever reopening or moving a checkout, run `node /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. + +- **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. + +## 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. + +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: + +```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; + // ... +} +``` + +## 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: + +- 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. + +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. + +Use SIWC for account pages, user-specific dashboards, saved records, and write actions tied to the current ChatGPT user. Leave public content anonymous. + +## Local D1 migrations + +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: + +```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 +``` + +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. + +## Diagnostic Commands + +- `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 + +When using the Sites plugin, follow its skill instructions for installation, builds, and publishing. These npm commands remain available for standalone use. + +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 + +- [vinext Documentation](https://github.com/cloudflare/vinext) +- [Drizzle D1 Guide](https://orm.drizzle.team/docs/get-started/d1-new) diff --git a/app/api/demands/route.ts b/app/api/demands/route.ts new file mode 100644 index 0000000..1b9bfe8 --- /dev/null +++ b/app/api/demands/route.ts @@ -0,0 +1,50 @@ +import { env } from 'cloudflare:workers'; +import { getChatGPTUser } from '../../chatgpt-auth'; +import { fieldSchema, missingFields, type Demand } from '@/lib/demand'; +export const dynamic='force-dynamic'; +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;} +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'}});} + 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); + try{ + const raw=await request.text();if(raw.length>80000)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; + 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('登记方式无效。'); + 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(); + }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'){ + 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);} + 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()}`; + }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); + } + return Response.json({demand:record},{headers:{'Cache-Control':'no-store'}}); + }catch(e){console.error('Demand save failed',e);return fail('保存失败,你的输入仍保留在页面中,请稍后重试。',503);} +} diff --git a/app/chatgpt-auth.ts b/app/chatgpt-auth.ts new file mode 100644 index 0000000..a0ae2ed --- /dev/null +++ b/app/chatgpt-auth.ts @@ -0,0 +1,90 @@ +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 new file mode 100644 index 0000000..e8a4729 --- /dev/null +++ b/app/globals.css @@ -0,0 +1,19 @@ +@import 'tailwindcss'; +@import 'tw-animate-css'; +@source '../components'; +@theme inline {--color-background: #fff;--color-foreground:#102247;--color-border:#dfe7f2;--color-ring:#1762f5;} +:root{--blue:#1762f5;--ink:#102247;--muted:#73829d;--border:#e1e8f2;--surface:#fff;--bg:#f6f8fc;--radius:10px;font-synthesis:none} +*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font-family:Inter,-apple-system,BlinkMacSystemFont,'PingFang SC','Microsoft YaHei',sans-serif;font-size:14px;line-height:1.6}button,input,textarea,select{font:inherit}button,a,input,select,textarea{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button{color:inherit}button:disabled{cursor:not-allowed;opacity:.5}button:focus-visible,a:focus-visible{outline:3px solid #a1bfff;outline-offset:3px}input:focus,textarea:focus,select:focus{outline:2px solid #b7d0ff;outline-offset:0;border-color:var(--blue)}a{color:var(--blue)}h1,h2,h3,p{margin:0}h1{font-size:30px;line-height:1.35;font-weight:650;letter-spacing:-.7px}h2{font-size:19px;line-height:1.5;font-weight:650}h3{font-size:15px;font-weight:600}svg{flex-shrink:0;stroke-width:1.8}.app-shell{min-height:100vh}.sidebar{position:fixed;width:224px;inset:0 auto 0 0;background:white;border-right:1px solid var(--border);z-index:20;display:flex;flex-direction:column;padding:25px 14px 16px}.brand{display:flex;gap:13px;align-items:center;padding:0 12px 30px}.brand-mark{width:32px;height:32px;display:grid;grid-template-columns:1fr 1fr;gap:3px}.brand-mark i{background:var(--blue);border-radius:4px}.brand-mark i:last-child{background:#578eff}.brand strong{font-size:25px;font-weight:700;letter-spacing:1px;display:block;line-height:1.25}.brand span{color:var(--muted);font-size:12px;display:block;margin-top:4px;letter-spacing:1px}.sidebar nav{display:flex;flex-direction:column;gap:7px}.sidebar nav button,.guide-nav{background:none;border:0;display:flex;align-items:center;gap:16px;text-align:left;padding:13px 15px;width:100%;border-radius:7px;font-size:15px;min-height:49px}.sidebar nav button:hover,.guide-nav:hover{background:#f5f8fc}.sidebar nav .active{color:var(--blue);background:#edf4ff;font-weight:600}.nav-count{font-size:12px;font-weight:500;display:flex;align-items:center;justify-content:center;width:21px;height:21px;margin-left:auto;background:#eef1f6;border-radius:50%;color:#536580}.nav-count.alert{background:#ffeded;color:#e24c56}.sidebar-bottom{margin-top:auto}.guide-nav{border-top:1px solid var(--border);border-radius:0;padding-top:22px;margin-top:30px}.profile{display:flex;align-items:center;gap:12px;padding:19px 13px 3px}.profile strong{font-size:14px;font-weight:500;max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.profile>svg{margin-left:auto;color:var(--muted)}.avatar{width:33px;height:33px;border-radius:50%;background:#e9f1ff;color:var(--blue);display:grid;place-items:center}.main-shell{margin-left:224px}.topbar{height:64px;display:flex;align-items:center;justify-content:space-between;padding:0 32px;border-bottom:1px solid var(--border);background:white}.topbar>span{display:flex;align-items:center;gap:14px}.topbar>span:first-child{color:var(--muted)}.topbar strong{font-weight:400;color:var(--ink)}.top-date{font-size:13px}main{padding:28px 32px 18px;max-width:1680px;margin:auto}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:23px}.page-heading p{color:var(--muted);margin-top:6px;font-size:14px}.btn{border:1px solid #d6dfed;background:white;padding:9px 14px;border-radius:6px;font-size:14px;font-weight:500;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:40px;white-space:nowrap;transition:background .15s,border-color .15s}.btn:hover{background:#f7faff;border-color:#abc6f4}.btn.primary{color:white;background:var(--blue);border-color:var(--blue);padding:10px 18px}.btn.primary:hover{background:#0d52dc}.plus{font-size:22px;line-height:20px;font-weight:400}.text-button{border:0;padding:0;background:none;display:inline-flex;align-items:center;gap:9px;color:var(--blue);font-size:14px;white-space:nowrap}.text-button:hover{text-decoration:underline}.stats{background:white;border:1px solid var(--border);border-radius:var(--radius);display:grid;grid-template-columns:repeat(4,1fr);padding:18px 0;margin-bottom:15px}.stats button{background:none;border:0;border-right:1px solid var(--border);display:flex;align-items:center;flex-direction:column;gap:3px}.stats button:last-child{border:0}.stats button:hover strong{color:var(--blue)}.stats span{font-size:14px;color:#425576}.stats strong{font-size:36px;line-height:1.2;font-weight:650;font-variant-numeric:tabular-nums}.reminder{display:flex;align-items:center;gap:15px;padding:14px 18px;border:1px solid #cfe0ff;border-radius:7px;background:#edf4ff;margin-bottom:20px;color:#425777}.reminder>svg,.reminder>strong{color:var(--blue)}.reminder strong{font-weight:550}.reminder-divider{height:16px;width:1px;background:#95b8ff;margin:0 1px}.reminder>.text-button{margin-left:auto}.workspace-grid{display:grid;grid-template-columns:minmax(0,1fr) 286px;gap:18px;align-items:start}.workspace-grid.full-width{grid-template-columns:1fr}.panel{background:white;border:1px solid var(--border);border-radius:var(--radius)}.demand-panel{overflow:hidden;min-height:520px}.panel-heading{display:flex;align-items:center;justify-content:space-between;padding:18px 20px 10px;gap:12px}.tabs{display:flex;gap:23px;border-bottom:1px solid var(--border);padding:0 20px}.tabs button{border:0;background:none;padding:11px 1px 12px;border-bottom:2px solid transparent;margin-bottom:-1px;white-space:nowrap;font-size:14px;color:#536482}.tabs button.selected{color:var(--blue);border-color:var(--blue);font-weight:550}.table-toolbar{padding:13px 17px;display:flex;gap:10px}.search-field{display:flex;align-items:center;gap:10px;padding:0 11px;border:1px solid #d6dfed;border-radius:6px;flex:1;min-width:0;color:#637798}.search-field input{border:0;background:none;height:37px;width:100%;min-width:0;outline:none!important;box-shadow:none}.search-field:focus-within{border-color:var(--blue);outline:2px solid #d9e7ff}.search-field input::placeholder{color:#8b9ab2}.filter-button{padding:7px 12px;min-height:38px}.pressed{color:var(--blue);border-color:#b6d0ff;background:#f0f5ff}.table-wrap{padding:0 10px 10px;overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:14px}thead{background:#f5f7fb}th{font-weight:500;padding:10px 12px;color:#5d6f8c;font-size:13px;white-space:nowrap}th:first-child{border-radius:6px 0 0 6px}th:last-child{border-radius:0 6px 6px 0}td{padding:14px 12px;border-bottom:1px solid #e8edf5}tr:last-child td{border-bottom:0}tbody tr:hover{background:#fafcff}td:first-child{width:44%}.demand-title{border:0;background:none;display:flex;align-items:center;gap:7px;padding:0;text-align:left;font-weight:550;line-height:1.6;font-size:14px}.demand-title svg{opacity:0;color:var(--blue)}.demand-title:hover{color:var(--blue)}.demand-title:hover svg{opacity:1}.row-meta{font-size:11px;color:#8391a9;display:flex;gap:6px;margin-top:4px;white-space:nowrap}.status{display:inline-flex;padding:3px 9px;border-radius:5px;font-size:12px;white-space:nowrap;line-height:1.65}.status.purple{color:#7440b9;background:#f1eafa}.status.blue{color:#1762d3;background:#eaf1ff}.status.green{color:#258354;background:#e8f5ec}.status.teal{color:#15827b;background:#e1f6f3}.status.neutral{color:#586a87;background:#edf0f6}.status.gray{color:#7b8798;background:#f0f2f5}.supplement{display:block;color:#b88024;font-size:11px;white-space:nowrap;margin-top:3px}.priority{font-size:13px;white-space:nowrap;display:inline-flex;align-items:center;gap:6px}.priority i{width:6px;height:6px;border-radius:50%;background:#e9a632}.priority.p0 i{background:#d42a51}.priority.p1 i{background:#ee6570}.date-cell{font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}.right-rail{display:flex;flex-direction:column;gap:16px}.tips-panel{padding:18px}.tips-panel h2{display:flex;align-items:center;gap:7px;font-size:17px}.tips-panel h2 svg{color:#45628c;display:none}.tip{display:flex;align-items:center;gap:12px;padding:16px 0;border-bottom:1px solid #edf0f6}.tip:last-of-type{border:0;padding-bottom:12px}.tip>span{height:32px;width:32px;flex-shrink:0;border-radius:50%;background:#eaf2ff;display:grid;place-items:center;color:var(--blue);font-size:19px;font-weight:550}.tip h3{font-size:14px}.tip p{font-size:12px;margin-top:3px;color:var(--muted)}.tips-link{display:flex;justify-content:flex-end;width:100%;margin-top:6px;font-size:13px}.process-panel{padding:16px 20px}.process-panel h2{font-size:17px}.process-panel ol{list-style:none;margin:15px 0 0;padding:0}.process-panel li{display:flex;align-items:center;gap:16px;font-size:14px;position:relative;padding-bottom:15px}.process-panel li:last-child{padding-bottom:0}.process-panel li:before{content:'';position:absolute;left:11px;top:24px;bottom:0;width:1px;background:#d9e4f7}.process-panel li:last-child:before{display:none}.process-panel li>span{font-size:12px;display:grid;place-items:center;width:23px;height:23px;border-radius:50%;border:1px solid #c9daf5;background:#f1f6ff;z-index:1}.process-panel li .current{background:var(--blue);border-color:var(--blue);color:#fff}.process-note{display:flex;gap:6px;align-items:center;color:#91a0b5;font-size:11px;border-top:1px solid #eef1f6;padding-top:12px;margin-top:15px}.workspace-footer{color:#8c99ad;font-size:12px;margin-top:14px;display:flex;justify-content:space-between;gap:20px}.workspace-footer button{border:0;background:none;font-size:12px;color:#778ba9;display:flex;gap:6px;align-items:center}.filters{display:flex;align-items:end;gap:15px;padding:0 18px 15px}.filters label{display:flex;flex-direction:column;gap:4px;color:#63748f;font-size:12px}.filters select{padding:5px 8px;border:1px solid var(--border);border-radius:5px;font-size:13px;background:white}.filters .text-button{margin-bottom:6px}.empty-state{text-align:center;padding:55px 20px;color:var(--muted)}.empty-state>svg{margin:0 auto 13px;color:#819bc4}.empty-state h3{color:var(--ink);font-size:17px}.empty-state p{margin:8px 0 20px}.table-footer{padding:15px 22px;color:var(--muted);font-size:12px;border-top:1px solid var(--border)}.muted{color:var(--muted);font-size:13px} +@media(min-width:1450px){main{padding:30px 32px}.workspace-grid{grid-template-columns:minmax(0,1fr) 320px;gap:20px}.demand-panel{min-height:558px}.tip{padding:19px 0}td{padding:17px 13px}.row-meta{font-size:12px}.demand-title{font-size:15px}.status{font-size:13px}.tip p{font-size:13px}.tips-panel{padding:20px}.process-panel{padding:18px 22px}.process-panel li{padding-bottom:17px}.stats{padding:19px 0}.reminder{padding:15px 18px}} +@media(max-width:1190px){.sidebar{width:198px}.main-shell{margin-left:198px}main{padding:26px 24px}.topbar{padding:0 24px}.workspace-grid{grid-template-columns:minmax(0,1fr) 250px;gap:15px}.brand{padding-left:7px;gap:10px}.sidebar nav button{padding:12px;gap:11px}.tabs{gap:18px}td{padding:13px 9px}.row-meta{font-size:10px}.demand-title{font-size:13px}.tips-panel{padding:16px}.tip{gap:8px}.tip p{font-size:11px}.date-cell{font-size:12px}.priority{font-size:12px}.status{font-size:11px}.reminder{font-size:13px;gap:10px}} +@media(max-width:1000px){.workspace-grid{grid-template-columns:1fr}.right-rail{display:grid;grid-template-columns:1fr 1fr}.demand-panel{min-height:0}.process-panel ol{margin-top:12px}.process-panel li{padding-bottom:8px}.process-note{display:none}.row-meta{font-size:12px}.demand-title{font-size:14px}.tip p{font-size:12px}.status{font-size:12px}.workspace-footer{flex-wrap:wrap}} +@media(max-width:720px){.sidebar{position:sticky;inset:0 0 auto;width:100%;height:auto;flex-direction:row;padding:10px 16px;border-right:0;border-bottom:1px solid var(--border);align-items:center;gap:18px}.brand{padding:0}.brand strong{font-size:20px}.brand span{display:none}.brand-mark{width:26px;height:26px}.sidebar nav{flex-direction:row;margin-left:auto;gap:3px}.sidebar nav button{padding:9px;min-height:38px}.sidebar nav button>span,.sidebar nav .nav-count{display:none}.sidebar-bottom{display:none}.main-shell{margin:0}.topbar{height:48px;padding:0 18px;font-size:12px}.top-date{font-size:11px;gap:6px!important}.top-date svg{width:14px}main{padding:23px 17px}.page-heading{align-items:flex-start;gap:12px}h1{font-size:25px}.page-heading p{font-size:12px;max-width:210px}.page-heading>.btn{font-size:12px;padding:8px 10px;min-height:36px;gap:3px}.stats{padding:16px 0}.stats strong{font-size:28px}.stats span{font-size:12px}.reminder{flex-wrap:wrap;padding:12px;gap:7px}.reminder-divider{display:none}.reminder>span:not(.reminder-divider){order:2;width:100%;padding-left:25px;font-size:12px}.reminder .text-button{font-size:12px}.reminder>strong{font-size:13px}.reminder>svg{width:17px}.panel-heading{padding:16px 16px 8px}h2{font-size:18px}.tabs{gap:22px;padding:0 15px}.tabs button{font-size:13px}.table-toolbar{padding:12px}.filter-button{font-size:12px;padding:7px 9px}.search-field input{font-size:12px}.table-wrap{padding:0 7px;overflow:auto}table{min-width:550px}.right-rail{grid-template-columns:1fr}.tip{padding:15px 0}.tips-panel{padding:18px}.tips-panel h2{font-size:17px}.tips-panel h2 svg{display:block}.tip p{font-size:13px}.process-panel{display:none}.workspace-footer{font-size:11px;gap:8px}.filters{flex-wrap:wrap;padding:0 12px 12px}.workspace-grid{gap:15px}} +@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} +@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}} diff --git a/app/layout.tsx b/app/layout.tsx new file mode 100644 index 0000000..ab1293a --- /dev/null +++ b/app/layout.tsx @@ -0,0 +1,4 @@ +import type { Metadata } from 'next'; +import './globals.css'; +export const metadata: Metadata={title:'需有序 · 需求登记管理',description:'面向业务方的需求登记、进度跟踪与验收协作平台。',icons:{icon:'/favicon.svg',shortcut:'/favicon.svg'}}; +export default function RootLayout({children}:Readonly<{children:React.ReactNode}>){return {children}} diff --git a/app/page.tsx b/app/page.tsx new file mode 100644 index 0000000..56f1be9 --- /dev/null +++ b/app/page.tsx @@ -0,0 +1,4 @@ +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 } diff --git a/build/sites-vite-plugin.LICENSE b/build/sites-vite-plugin.LICENSE new file mode 100644 index 0000000..4243cb4 --- /dev/null +++ b/build/sites-vite-plugin.LICENSE @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000..2ece1b9 --- /dev/null +++ b/build/sites-vite-plugin.ts @@ -0,0 +1,230 @@ +// 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 new file mode 100644 index 0000000..856e090 --- /dev/null +++ b/cloudflare-env.d.ts @@ -0,0 +1,6 @@ +declare namespace Cloudflare { + interface Env { + DB?: D1Database; + BUCKET?: R2Bucket; + } +} diff --git a/components.json b/components.json new file mode 100644 index 0000000..c8f5bb1 --- /dev/null +++ b/components.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "registries": {} +} diff --git a/components/demand/app.tsx b/components/demand/app.tsx new file mode 100644 index 0000000..40844b8 --- /dev/null +++ b/components/demand/app.tsx @@ -0,0 +1,36 @@ +'use client'; +import { useState, useEffect, useRef, useCallback } from 'react'; +import { House, Files, SquareCheck, Folder, BookOpen, CalendarDays, ChevronRight, UserRound, CheckCircle2, CircleAlert, RotateCw } from 'lucide-react'; +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'; +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]); + 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()},[]); + 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)}}/>} +
+ {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}/>} + {toast&&
{toast}
} +
; +} diff --git a/components/demand/dashboard.tsx b/components/demand/dashboard.tsx new file mode 100644 index 0000000..b5dcf9e --- /dev/null +++ b/components/demand/dashboard.tsx @@ -0,0 +1,25 @@ +'use client'; +import { useState } from 'react'; +import { ArrowRight, Bell, ChevronRight, Search, SlidersHorizontal, FileText, Lightbulb } from 'lucide-react'; +import { type Demand, needsAction } from '@/lib/demand'; +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}){ + const [tab,setTab]=useState('全部需求');const [query,setQuery]=useState('');const [filterOpen,setFilterOpen]=useState(false);const [priority,setPriority]=useState('全部优先级');const [project,setProject]=useState('全部项目'); + 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 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=>)}
} +
+ {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?'试试其他关键词或调整筛选条件。':'把业务问题写下来,让每一步都有据可循。'}

} + {view!=='我的工作台'&&rows.length>0&&
共 {rows.length} 条,已显示全部结果
}
+ {view==='我的工作台'&&}
+
{demo?'当前展示示例数据,登记后将进入你的工作空间。':'期望上线为业务期望,正式交付时间以评审计划为准。'}
+ ; +} diff --git a/components/demand/detail.tsx b/components/demand/detail.tsx new file mode 100644 index 0000000..eddbc04 --- /dev/null +++ b/components/demand/detail.tsx @@ -0,0 +1,38 @@ +'use client'; +import { 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 { Status } from './dashboard'; +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]); + 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{}} + 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=>)}
+
+ {(error||localError)&&
{error||localError}
} + {d.demo&&
当前为示例需求,验收和变更操作只用于体验,不影响实际业务数据。
} + {mode==='change'||mode==='cancel'?

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

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

{mode==='change'&&