feat: 按 nex.config.yaml 技术栈重写前端 + 表单统一侧滑 + 正文富文本

- 前端栈换成 React 19 + TS + Vite + AntD 6 + Tailwind v4 + Zustand + React Router 7 + Axios,八个视图全部迁完;旧版留在 web/legacy/
- 新增 / 修改表单统一右侧侧滑(components/FormDrawer.tsx,12 处);删除等破坏性确认仍保持弹窗
- 录入字段与「更新录入」口径对齐;长文本录入位统一富文本编辑器(内核 Tiptap 3,颜色存语义名 data-c 而非 hex,跟着主题 token 走)
- 展示端用 RichText 渲染 + 两行 clamp;app/export.py 的 plain() 在出表时统一降级成纯文本,三端换行口径一致(一个块级 = 一个换行)
- tests: 富文本存储契约与出表断言入契约测试;pytest 104 passed
main
mula.liu 2026-11-19 09:32:38 +08:00
parent 139f5ca959
commit a0ced813c5
137 changed files with 15163 additions and 2244 deletions

2
.dockerignore 100644 → 100755
View File

@ -20,6 +20,8 @@ scripts/run.sh
scripts/deploy.sh
scripts/legacy
tests
web/node_modules
web/dist
requirements-dev.txt
docker-compose.yml
Dockerfile

0
.env 100644 → 100755
View File

0
.env.example 100644 → 100755
View File

0
.workbuddy/memory/2026-09-12.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-13.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-14.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-16.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-17.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-18.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-20.md 100644 → 100755
View File

0
.workbuddy/memory/2026-09-23.md 100644 → 100755
View File

0
.workbuddy/memory/2026-10-01.md 100644 → 100755
View File

0
.workbuddy/memory/2026-10-29.md 100644 → 100755
View File

0
.workbuddy/memory/2026-10-30.md 100644 → 100755
View File

0
.workbuddy/memory/2026-11-04.md 100644 → 100755
View File

View File

@ -0,0 +1,22 @@
# 2026-11-12 工作日志
按新引入的 NEX Design System 0.1.7(`nex_design_system/` + `nex.config.yaml`)完整改造前端。**技术栈没动**(FastAPI + 零构建原生 JS + SQLite,NEX §2:已有项目以真实代码为准),改动只落在 `web/` 四个文件 + README/MEMORY 口径,后端一行未改(103 例 pytest 全绿,含前后端参数契约测试)。
## 改了什么
1. **`styles.css`(700 → 985 行):token 单一来源**。顶部 `:root` 重写成语义层(`--text/--text-2/--muted/--surface-*/--primary*/--success/--warning/--danger/--radius-*/--sp-*/--ctrl-h-*/--shadow-*/--dur-*/--z-*/--h-topbar/--sidebar-w`),断点登记注释 1180/1100/900/780/640;`.pill/.tag-mini/.arch-badge` 改成只吃 `--c` + `color-mix()` 派生(废掉成对 hex);新增 `.page-head/.dlg-title/.link-btn/.th-sort/.tabpanel/.sk*(骨架)/.sr-only/.skip-link/.is-archived/.trunc`;补 1100 抽屉式侧栏 + 折叠按钮、900 顶栏换行 + 抽屉全宽、640 单列表单 + 底部弹窗 + 40px 触控高度;`prefers-reduced-motion` / `forced-colors` 兜底;auth 页渐变局部化为 `--auth-*`。
2. **`index.html`(117 → 129 行)**:`<main id="mainContent" tabindex="-1">` + skip-link + landmark;品牌标题 `<strong>`→`<h1>`;`nav aria-label` + 当前项 `aria-current`;周期段控件 `role="group"` + `aria-pressed`;抽屉/弹窗/登录框补 `role="dialog" aria-modal aria-labelledby` 与 `.dlg-title`;toast 改 `role="status" aria-live="polite"`;图标按钮补 `aria-label`。
3. **`app.js`(4191 → 4345 行)**:新增 `INK`(数据色常量,JS 模板里 hex 归零)、`VIEW_META/pageHead()`(八视图统一 h2 抬头 + 说明)、`loadingHtml()`(11 处「加载中…」文本 → 骨架)、`openLayer/closeLayer/focusableIn`(焦点进入 + Tab 锁层 + 关闭归还,三个抽屉入口都接上)、`withBusy()`、`bindTablist()`、`download(url, btn)` 忙态;弹层标题 → `h2.dlg-title id=modalTitle`;`starMark` 有语义(`role="img" aria-label`);卡片头 h4→h3、区块标题 div→h4、`ro()` 四份重复合成一份;排序表头 → `<th aria-sort>` + `.th-sort` 按钮;定制/权限页签 → tablist/tab/tabpanel;分页 → `<nav>` + `aria-current`;23 个图标按钮补名;`<a href="javascript:;">` → `<button class="link-btn">`;表格容器 `role="region" tabindex="0"`;108 个裸 `<label>` 全部要么 `for` 关联、要么改 `.fld-label`(现在 0 裸标签);错误槽 `role="alert"`;导出按钮 `disabled + aria-busy`;用户菜单补 `role=menu/menuitem/aria-expanded` + Escape。
4. **`icons.js`**:加 `menu` 图标;自动前导图标的选择器跟 `.card-head h3` 同步。
5. **README「界面设计语言」/ MEMORY.md**:补 token 单一来源、`--c` 算法、弹层焦点、状态不靠颜色、断点登记五条长期口径。
## 踩到的两个坑(记下来)
- 全局「hex → token」批量替换把 **`:root` 自己**也替换了,产出 12 条 `--panel: var(--panel)` 自引用 → CSS 整段失效白屏;同类误伤还有局部 `z-index: 2` 被提成全局 `--z-*`(页签压住顶栏)和非控件几何被换成 `--ctrl-h-*`(图标底板变长方形)。批量映射必须排除定义区。
- 给 `<label>` 加 `for` 的正则把控件开标签 **id 之后的属性全吞了**(80 个 input/select 丢 `value/type/placeholder/data-autofocus`),靠 `git show HEAD:web/app.js` 按前缀 + id 逐个还原。教训:改写开标签要捕获整段 `[^>]*>`,别只捕获到 id。
## 验证
- `node --check web/app.js` / `icons.js` 通过;`.venv/bin/python -m pytest -q` → **103 passed**。
- 浏览器(`frontend-verify`):八视图逐一点开,控制台 0 错误 0 失败请求;`.wk-split` 两栏、`.wk-head-ops` 归位;Tab 首落 skip-link → 回车跳到 `<main>`;新建项目弹窗首落 `#npName`、连按 Tab 锁在层内、Esc 归还到触发按钮;详情抽屉同上;定制页表头 `aria-sort` 切换、三页签 `aria-selected` 正确;390px / 820px iframe 下侧栏转抽屉、顶栏换行、KPI 两栏、无横向溢出。
- **未提交**(等确认);未做:`refresh()` 切周期的请求竞态守卫、RBAC 行内写操作的部分 `withBusy` 覆盖、`ro()/on()/stat()` 之外剩余重复块的抽取——都是 P2/P3,界面行为已合规。

View File

@ -0,0 +1,76 @@
# 2026-11-13 工作日志
按用户要求把前端换成 `nex.config.yaml` 声明的 nex-standard-fullstack:**React 19 + TypeScript + Vite + Ant Design 6 + Tailwind CSS v4 + CSS Variables + Zustand + React Router 7 + Axios(lockfile 必交)**。后端 FastAPI/SQLite、接口、业务流程与默认值一行未改(103 例 pytest 全绿)。这是用户明确要求的迁移,覆盖了 NEX §2「已有项目不迁移」。
## 落地的结构与长期口径(后续前端改动照这几条走)
- `web/src/` 是唯一前端源码;`web/dist/` 是构建产物(不入库);`web/legacy/` 是改造前的零构建版,**只在没有 `dist` 时被 `app/main.py` 当作兜底**,同时保留作业务口径对照。
- **Token 单一来源仍是 `web/src/styles/tokens.css` 的 `:root`**(阶段一成果):Tailwind v4 只通过 `@theme inline` 指回同一批变量,AntD 主题在 `web/src/theme/antd.ts` 里读同一批色值并带 dev 期漂移告警(`assertTokensMatch`)。任何新色值先进 `:root`,不要在组件里写 hex。
- **查询参数集中在 `web/src/api/endpoints.ts`**:一个接口一个函数,视图只允许传该函数点名的键,没点名的会被静默丢掉。`tests/test_api_contract.py::test_前端查询参数必须在后端有声明` 据此对表 OpenAPI(get/del 比 parameters,写请求比 requestBody schema)。加接口就改这一个文件。
- 界面状态在 `web/src/store/ui.ts`(Zustand + 手写 sessionStorage 持久化,键 `unis.ui.v2`,字段与旧版 `state` 同名 + `sanitize()` 防呆);字典/周期/台账缓存在 `store/meta.ts`(`dataRev` + `bump()` 是全站刷新信号);会话与权限在 `store/session.ts`(`useCan().r/w(menu)`)。
- 反馈只三条通道:弹层内错误用行内 `<Alert type="error" showIcon title>`(AntD 6 已把 `message` 改名 `title`);其余用 `App.useApp().message`;破坏性动作 `modal.confirm`(危险按钮 `okButtonProps:{danger:true}`)。导出统一 `download(url, btn, message)`(fetch+blob,按钮 `disabled + aria-busy`)。
- 弹层/焦点不再自研:Modal/Drawer 一律 AntD(自带 `role=dialog`、焦点陷阱、Esc、焦点归还);图标仍是项目自有 `web/src/icons`(52 个 24×24 线性 SVG),AntD 自带图标不参与业务语义;`ConfigProvider autoInsertSpaceInButton={false}` 保证按钮文案与旧版逐字一致。
- 顶栏控件按视图给(旧版 `setView` 名单):周期条只在 `board/projects/custom/focus/intake`,搜索框只在 `board/projects/custom/focus/staff`。周期口径 helper(跨月周摊算、下拉标签)统一在 `web/src/utils/period.ts`,新建周期弹窗统一在 `components/NewPeriodModal.tsx`。
## 追加:新增 / 修改面板统一为侧滑(用户要求)
- 12 处表单弹窗全部换成右侧抽屉,统一走新增的 `components/FormDrawer.tsx`(取消 + 保存/创建 固定右下、提交中 busy 时禁 Esc、层内 Alert 报错、窄屏全宽):个人设置、新建周期(顶栏下拉与设置页共用)、新建项目、添加·修改执行记录(自研 + 看板两套)、添加·修改交付记录、新建定制项目(定制页 + 录入页)、新增·编辑人员、新建·修改角色、新建·编辑用户、重置密码。
- **删除类保持弹出确认**:`modal.confirm`(危险按钮)与需要逐字输入名称的删除弹窗(项目、定制项目)不是「新增 / 修改表单」,没跟着改。
- 表单内容一律原样搬进抽屉,字段顺序、标签、校验文案没动。
## 追加:录入字段一致 + 正文富文本(用户提的两条)
- **字段对齐**:各模块的「添加/修改执行记录」「添加/修改交付记录」补齐了「一句话摘要」(后端 Update.summary / CustomUpdate.summary 一直支持,前端从没填过),标签措辞改成与更新录入页一致:内容 *→执行内容(正文,原文照录)*、进度(%)→总进度(定制为开发进度(%))、状态→整体状态、风险→风险 / 阻塞、下一步→下一步计划。自研的「子任务」保留(录入页不建子任务,属于模块特有的轴)。
- **正文富文本**:新建 `web/src/components/RichEditor.tsx`(加粗/下划线/斜体/5 个语义色/清除格式,contentEditable + execCommand,不引第三方库)与 `RichText.tsx`(消毒后注入),约定写在 `web/src/utils/richtext.ts` 顶部:只允许 `<b> <i> <u> <br> <span data-c="语义名">`,颜色存语义名不存 hex,显示时映射 var(--*) token,于是改主题会跟着变;旧的纯文本数据不用迁移(换行转 `<br>`)。
- 接的位置:执行记录(自研页 + 看板)、交付记录(定制页 + 看板)、更新录入的「整理结果」正文(自研/定制两处)、重点工作的说明与结果反馈;展示端 UpdItem / 阶段流转 / 列表截断(先 `richToText` 再切,否则会把标签切一半)。「原始内容」粘贴框故意保持纯文本,掺标记会打乱规则解析的分行与提示词。
- 后端:`app/export.py` 加 `plain()`(标签剥掉、`<br>` 变真换行、实体还原),`build_xlsx` 每个单元格过一遍,六张表都跟着降级;导出关键词匹配也改成在纯文本上比(重点工作的量小,排序后再筛)。契约测试 `tests/test_api_contract.py::test_正文富文本按约定存_按纯文本出表` 钉住这套约定(含「项目名里的尖括号不能误伤」)。
- 踩坑:execCommand 只吃具体色值,浏览器给的 `<span style="color:#hex">` 或 `<font color>` 要在提交前换回 `<span data-c>`(`normalizeColors`,色表按主题算一次缓存);工具栏按钮点下去会抢焦点导致选区丢失、格式打不上,必须 `onMouseDown preventDefault` + 失焦时存 Range、下次恢复。
- 验证:tsc 0 错、`vite build` 通过、`104 passed`;浏览器实测在看板新建一条正文加粗+标红的记录,库里存回来是 `<b><span data-c="danger">…</span></b>`,时间线渲染红色计算值 `rgb(180, 35, 24)`(= `--danger-strong`),截图后把这条测试记录删掉了;重点工作抽屉两个富文本框正常、0 控制台错误。更新录入的「整理结果」预览这次没等到(点了 AI 整理一直「整理中…」,本机 AI 接口没配/超时),改动只是把 TextArea 换成同一个组件,编译与另外三处同路径。
## 第一轮用户验收(两个返工点)
- 用户反馈「加了富文本但显示时没有富文本」。原因在我:列表 / 卡片那类预览我沿用旧版的「先转纯文本再按字数截断」(`richToText(...).slice(0,48)`),格式在这一步就被抹平了;抽屉详情是好的,所以他看到抽屉里对、列表里不对。改法:所有展示这些字段的地方一律 `<RichText/>`,需要截断的地方加 `className="clamp"`(app.css 里 `-webkit-line-clamp: 2`),不再数字数。改到:每周工作的说明 / 结果反馈列、看板交付行的摘要、定制台账备注列、三个模块 UpdItem 的风险 / 下一步、定制备注行、看板卡片备注。
- 第二条要求是「需要输入富文本的地方都加统一编辑器」。把剩下的长文本框全铺上同一个 `RichEditor`:执行 / 交付记录的 风险 / 阻塞 与 下一步计划(自研页、定制页、看板)、定制项目备注(新建 + 抽屉编辑 + 录入页新建)、更新录入的「原始内容」粘贴框(自研 + 定制两处)与整理结果里的 风险 / 下一步。单行字段(一句话摘要、重点工作「工作内容」)故意不铺,格式在那里没意义。
- 「原始内容」铺富文本的代价与处理:规则解析器 `app/ai_parser.py` 是按行找「风险 / 下一步」的,标记会打断它。所以发给 `/ai/parse` 的那份先 `richToText`(块级标记还原成换行),直接写入与 AI 写入入库的正文仍带标记(`/ai/commit` 是 `content = raw_text`,保格式)。整理结果的风险 / 下一步要发数组给后端,新增 `richToLines()`:按 `<br>` 与块级标签拆行,行内 `<b>/<span data-c>` 跟着这一行走,否则用户给某一行上的色会在保存时静默消失。
- 浏览器实测:每周工作列表说明列与自研时间线都是加粗+标红(红色计算值 `rgb(180, 35, 24)` = `--danger-strong`);五个页面正文里都不露尖括号标签、控制台 0 错误;看板抽屉 3 个富文本框、定制 1 个、重点工作 2 个、录入页 1 个,字段齐;录入页直接写入端到端跑通(测试记录已删)。`tsc 0 / vite build 通过 / pytest 104 passed`。
- 坑(记一下):Playwright 的 `type` 是 fill 语义,整段替换 contentEditable 的内容,所以「先点加粗再打字」在这种自动化里看不到 `<b>`(真人打字是有格式的,execCommand 的 typing state 在)。要在自动化里验证富文本,得先输入再选中再点工具栏(`press Shift+End`)。
## 编辑器重做(用户第二轮反馈:不像标准编辑器 + 输入有问题)
- 「输入有问题」是真的:我在 `emit()` 里做 `el.innerHTML = 归一后的字符串`,每次按键都把 DOM 重排一遍 → 光标回到开头,逐字敲 abc 得到 **cba**。改法:编辑区改成**非受控**——只有外部回填且焦点不在里面时才写 DOM;归一「只改属性、不重排」;`compositionstart/end` 期间不抛值(中文输入法候选词会被打断)。Playwright 逐字符 `press` 复现最快,`type`(fill 语义)反而看不出来。
- 工具栏改成标准排布:图标按钮(`bold/italic/underline/eraser/chevron-down` 五个图标加进唯一图标层 `icons/paths.ts`)+ 颜色按钮(A + 当前色条 + ▾)弹出**色板面板**(AntD Popover,6 格:默认色 + 5 个语义色,当前色带勾);`aria-pressed` 跟着选区状态走;Esc 先关面板再关抽屉(`stopPropagation`)。
- 上色不再走 `execCommand("foreColor")`:那条路要「浏览器给 hex/rgb 的 span 或 font 标记 → 我们再换算回语义色」,各内核还不一样,实测选区上色直接被下一环吃掉。改成 `Range` 手工包 `<span data-c>`:选区有内容就 extractContents 后包一层(顺带摘掉途经的旧色,替换语义不嵌套);光标处点色就插一个零宽占位 span 并把光标放进去,紧接着打的字带色,失焦时若没打字把占位清掉。
- 三个连环坑(都是「颜色点了没反应」):① 色板面板是 portal 出去的,点色块会抢走焦点、选区被吞 → 面板也要 `onMouseDown preventDefault` 并在打开时 `saveRange()`;② `normalizeInPlace` 把我自己刚包的 `<span data-c>` 当成浏览器野标记解包了(要先认自己的标记);③ CSS 里写了不存在的 `--primary-strong`/`--success-strong`,`var()` 失效就退回继承色,看着像「没上色」——语义色映射统一用真实 token:`--danger/--warning/--primary/--success/--muted`。
- 验证(逐字符键入 + 局部选区上色):`abcd` 顺序对、光标位置对;局部加粗只包中间两字 `红橙<b>蓝绿</b>灰`;连点五色只剩一层(不嵌套);「默认色」摘色保留加粗;五种语义色计算值与 token 一致(蓝 = rgb(37,99,235));看板新建一条加粗标红的执行记录,库里存 `<b><span data-c="danger">…</span></b>`、时间线渲染 rgb(220,38,38),测完删掉。`tsc 0 / vite build 通过 / pytest 104 passed`。
- 遗留:更早那一版编辑器留下的嵌套 span(`<span data-c=danger><span data-c=primary>`)在旧数据里还在,显示以内层为准,没做一次性清洗(要洗就一条 SQL 的事,等用户点头)。
## 换内核:Tiptap 3(用户第三轮反馈:色板别写中文 / 回车有问题)
- 色板去掉中文标签,只留 6 个色块(第一个是「无色」,白底 + 红斜杠,比白底在深色主题下更清楚);名字进 `title` / `aria-label`,当前色描一圈。
- 回车确实是坏的:Chrome 的 contentEditable 用 `<div>` 分块,双回车多一整行空行、行首回车还会把字放错位置(逐字符 `press` 复现:`a<div>b</div><div><br></div><div>c</div>`,innerText 4 行变 5 行)。手写追不完,经用户同意换 Tiptap 3.34(`@tiptap/react` + `@tiptap/pm` + `starter-kit` + `extension-text-style` + 显式 `extension-bold/italic`),React 19 peer 兼容。
- 换内核后仍然要守三件事,都是踩出来的:
1. 官方 `Color` 扩展存 hex,会脱离主题 token;自己写 `TableStyle` 上的 `data-c` 属性(`TextStyle.extend` 改 `parseHTML/renderHTML`)。注意 `TableStyle.parseHTML` 默认要求 `span` 带 `style` 属性才认,我们旧数据是 `<span data-c>` 没 style,不改 `getAttrs` 就解析不进来。
2. 加粗/斜体默认产 `<strong>/<em>`,不在展示端白名单里(会被解包成纯文本,加粗当场消失)→ `Bold.extend`/`Italic.extend` 只发 `<b>/<i>`,收还是两种都收;`sanitizeRich` 也加了 STRONG→B / EM→I 的别名映射兜粘贴进来的内容。
3. `getHTML()` 的空段落是 `<p></p>`,展示端没有行盒 → 编辑时看得见的空行保存后消失。`normalizeOut` 里补成 `<p><br></p>`,另外 `.rich-view p:empty` 给个 `min-height` 兜旧数据。
- 换行口径三端对齐:`richToText` 改成 DOM 走一遍(块前/块后各补一个换行,绝不双计),`app/export.py.plain()` 加 `_ADJACENT_BLOCK` 先把相邻 `</p><p>` 合成一个换行再断;契约测试补了两条断言钉住(`plain("<p>L1</p><p>L2</p><p><br></p><p><b>L4</b></p>") == "L1\nL2\n\nL4"`)。
- 实测:逐字符输入顺序对、光标对;`Ctrl+A` 跨四段选区点色 → 每段各自一个 `<span data-c>`、空段 `<p><br></p>`,入库与编辑区一字不差;只读抽屉正好 4 行(含一个空行),橙 = `--warning`;导出说明列 `'L1 aaa L2 bbb L4 ddd'`(换行按老规矩变空格);`Ctrl+Z` 撤销/重做可用(ProseMirror 自己的历史栈,比 `execCommand` 靠谱);用户那条嵌套 span 的旧数据(`<span data-c=primary><span data-c=muted><b>`)在新编辑器里正确回显、颜色按内层。`tsc 0 / build 通过 / pytest 104 passed`,四个视图抽屉里编辑器都在、控制台 0 错误、正文没有裸标签泄漏。
- 代价:新增 6 个 `@tiptap/*` 包;`RichEditor` 独立 chunk 130.78 kB gzip(Vite 自动切的,不在首屏 preload 里,跟着用到它的视图 chunk 走)。要再瘦就把组件 `React.lazy` 到抽屉打开时。
- 备注:`/focus` 那个抽屉是业务详情抽屉 `FocusDrawer`(`fc-drawer`),不是 `FormDrawer`,所以页面上没有 `.form-drawer` 类名——我测试时选错选择器误判过一次「抽屉打不开」。
## 踩到的坑(都写进工程了)
- 本仓库在共享盘挂载上:`npm install` 会 `EPERM chmod`(要 `--no-bin-links`,代价是 `node_modules/.bin` 为空 → 只能 `node node_modules/vite/bin/vite.js` 直调);`tools.write` 同因失败 → 一律 Node `fs.writeFile`。`scripts/run.sh` 已对这两点做了自动降级。
- `vite.config.ts` 必须 `base: "/static/"`,否则 FastAPI 的 `/static` 挂载与深链 SPA 回退对不上。
- 契约测试从「扫 app.js 字符串」换成「扫接口层」时,写请求要拿 requestBody schema 的属性比,不能拿 parameters 比,否则 `label/values` 这类 body 键全成误报。
- 迁移期最大的时间黑洞是**并行改同一批共享件**:子代理各自复制了 `NewPeriodModal`/周期 helper/`fetchHealth`/`refreshMeta`,回收成共享件后它们的视图才收敛。下次同类迁移应当先把共享层写完再派视图。
## 验证(2026-11-13 上午)
- `cd web && node node_modules/typescript/bin/tsc --noEmit` → **0 错**(八个视图 + 共享层全项目);`vite build` 通过(首屏 index JS ~945KB / CSS 40.8KB,八个视图各自切 chunk)。
- `.venv/bin/python -m pytest` → **103 passed**(后端只动了 `app/main.py` 静态托管与两处注释)。
- 构建版 `http://127.0.0.1:5173` 逐视图走查,控制台 0 错误 0 失败请求:看板(KPI 五卡对 `/api/custom/finance` 原值、左栏三分组、右栏四种分支、月/周切换、负责人筛选、导出 xlsx、抽屉与弹窗)、自研(列表 + 项目抽屉 + 按周/月反馈 + Esc 焦点归还)、定制(三 tab、130 条 21 列、年度 Q4 本季度标记与目标合计 680 / 64.3%、抽屉含交付环节与收入确认)、每周工作(分堆计数 0/0/3/19、表头吸顶 + 操作列吸右)、人力(归属统计 + 22 人花名册)、录入(两形态两模式 + 写入周期标签)、设置(三张卡 + 60 条周期分页 + 禁用删除原因气泡)、权限(四 tab:矩阵 / 用户 2 / 会话 7 / 日志 70)。
- 全局搜索联动:顶栏输入「云桌面」→ 自研列表 5 → 1 条,320ms 防抖生效。
- `app.css` 结构层删掉 31 组没人用的规则(旧版 modal/drawer/skeleton/pager/登录页与 AntD 取代的部分),1057 → 973 行;删后布局与样式复测正常(`.wk-split` grid、`.sidebar` sticky 宽度不变)。备份在 `/tmp/app.css.bak`。
- `web/legacy/` **保留**:没有 `web/dist` 时的兜底 + 业务口径对照;`app/main.py` 自动择优加载。
## 还欠的技术债(下次动前端时优先收)
- 视图里仍有几份局部复制的共享件:`focusBuckets`、`customWeeklySections`(+`CM_DEFAULTS/cmList/isPlaced`)、执行记录弹窗(project/custom 两套)、`PipelineBar`、`Pre/UpdItem`、`scopeRangeOf`,以及吸顶表格壳与图标按钮复位样式 —— 建议抽 `utils/focus.ts`、`utils/customSections.ts`、`components/UpdateRecordModal.tsx`、`components/PipelineBar.tsx` 并把样式并进 `app.css`。
- 只读角色(某菜单只有 r)的界面分支没有账号可实测(本机只有 admin),逻辑都是 `useCan().w(menu)` 判定,需要在有普通账号的环境再走一遍。

3
.workbuddy/memory/MEMORY.md 100644 → 100755
View File

@ -16,7 +16,7 @@
- `app/` 后端:`main.py`(入口,挂载 `/api` 子应用 + `/static`)、`models.py`、`schemas.py`、`constants.py`、`routers/{board,projects,custom,focus,weekly,staff,ai,export}.py`、`ai_parser.py`、`export.py`、`schema_patch.py`、`config.py`。
- `app/finance.py`(定制项目财务口径**唯一入口**)、`app/audit.py`(操作日志写入)。
- `web/` 前端:`index.html` / `app.js` / `styles.css` / `icons.js`(零构建,no-cache + ETag)。
- `web/` 前端:**已换成 nex.config.yaml 标准栈**(React 19 + TS + Vite + AntD 6 + Tailwind v4 + Zustand + React Router + Axios,源码 `web/src/`,产物 `web/dist/` 由 FastAPI 托管)。`web/legacy/` 是改造前的零构建版,没有 `dist` 时兜底。**设计 token 单一来源是 `web/src/styles/tokens.css` 的 `:root`**(NEX 0.1.7):JS 只注入 `--c` 数据色;查询参数集中在 `web/src/api/endpoints.ts`(契约测试据此对表 OpenAPI)。**设计 token 单一来源是 `styles.css` 顶部 `:root`**(NEX 0.1.7 改造,2026-11-12):JS 只注入 `--c` 数据色,弹层焦点走 `openLayer/closeLayer`,口径见 README「界面设计语言」。
- `tests/` + `pytest.ini` + `requirements-dev.txt`:接口级测试(102 例,`./.venv/bin/python -m pytest`),`conftest.py` 把库指到临时文件,**不碰 `data/board.db`**。
- `scripts/`:启动/部署 `run.sh`、`deploy.sh`;建库 `init_db.py`;数据导入 `import_excel.py`、`import_staff.py`、**`import_custom_ledger.py`**(《定开项目.xlsx》市场台账 → `custom_projects`,支持 `--dry-run`/`--date`,按 项目ID→名称 upsert)。
- `scripts/legacy/`:历史一次性脚本(`migrate_custom.py`、`shift_year.py`、`fix_period_split.py`、`merge_project.py`、`add_entry_date.py`),不参与启动、不进镜像。
@ -107,3 +107,4 @@
- 查端口占用:`netstat -ano | grep "127.0.0.1:8770.*LISTENING"`
- 停服务:git bash 下 `taskkill //PID` 会被路径转换破坏参数,改用 PowerShell `Stop-Process -Id <PID> -Force` 更稳。
- 服务重启后 `/health` 的 `BOOT_ID` 会变,可据此确认是新进程。
- 2026-11-13:前端按 nex.config.yaml 换成 React+TS+Vite+AntD+Tailwind v4+Zustand+Router+Axios(`web/src`,产物 `web/dist`,`web/legacy` 留作兜底)。长期口径与验证记录见 `.workbuddy/memory/2026-11-13.md`。

64
AGENTS.md 100755
View File

@ -0,0 +1,64 @@
# NEX Design System — Agent Development Rules (0.1.7)
NEX 的目标是统一设计规范并约束 Agent 开发行为。NEX 不负责测试体系、测试覆盖率、自动化测试、质量闸门或测试报告。
## 1. 每个任务的最小读取范围
开始任务时读取:
1. 本文件;
2. 项目根目录 `nex.config.yaml`(如存在);
3. 项目根 `AGENTS.md` 中的项目规则;
4. 项目已有的 UI/UX 规范(如存在)。
然后**按任务读取** NEX 文档,不得默认全量读取:
- 视觉风格/页面:`docs/01-design-principles.md`、`docs/08-page-patterns.md`;
- 颜色/主题/Token:`docs/02-design-tokens-and-theme.md`;
- 页面布局/导航/移动端:`docs/03-layout-and-responsive.md`;
- 公共组件:`docs/04-component-system.md`;
- 表单/表格/弹层/反馈:`docs/05-interaction-system.md`;
- 语义/键盘/辅助技术支持:`docs/06-accessibility-design.md`;
- 体验性能/加载呈现:`docs/07-performance-aware-design.md`;
- 新项目技术栈:`docs/10-project-stack-defaults.md`;
- 首次接入:`docs/11-project-adoption.md`。
## 2. 新项目与已有项目
- 新项目:`nex.config.yaml` 的 `stack` 是明确技术选型。按它初始化,不得自行换栈。
- 已有项目:以真实代码、依赖和锁文件为准,保留现有技术栈;不得因为 NEX 默认值不同而迁移。
- 项目具体视觉参数、Token 名称、组件 API、布局尺寸和断点以项目级 UI 规范为准。
## 3. 开发时必须遵守
1. 先理解现有页面和组件,再改代码;优先复用,不重复造组件。
2. 使用项目既有 Token 和主题单一来源,不另建重复变量层。
3. 保持同类页面、组件和交互的一致性。
4. 不擅自改变业务流程、交互路径、默认值或数据语义。
5. 不擅自升级依赖、替换 UI 库、改变语言或重构目录。
6. 仅修改完成当前任务所需的范围;不顺手重构无关页面。
7. 响应式、无障碍和体验性能按对应设计规范实现;不把这些要求扩展成 NEX 自建测试流程。
8. 若项目实现与 NEX 示例不同,先判断是否是合理的项目适配,不强制套用示例尺寸或命名。
9. 设计要求有冲突时,以安全/适用规范底线、项目级 UI 规范和用户明确要求为依据;无法确定时只提出一个关键问题。
## 4. 执行方式
默认采用轻量开发:
- 对当前需求做必要分析;
- 查找相关现有组件、Token、页面模式;
- 读取相关 NEX 章节;
- 直接实施必要修改;
- 在对话中简要汇报文件和行为变化。
只有涉及全局 Token、应用 Shell、导航体系、共享组件 API 或大范围视觉统一时,才先提交简短影响说明和实施计划。
## 5. NEX 的文件和工具边界
- 普通任务不得创建阶段报告、审计报告、`reports/` 目录或截图证据目录。
- 不得为了遵守 NEX 新建 `scripts/ui/`、自定义检查脚本、自动化测试或质量闸门。
- 不得自动引入 Playwright、axe、Vitest、Pytest 或其他测试工具;它们由项目自身工程规范决定。
- 不得启动 VoiceOver、NVDA、Orca 等屏幕阅读器;NEX 不定义其测试流程。
- 不得把 NEX 规范文档复制成项目中的第二套完整 UI 规范。项目只需保留必要的项目专属设计说明。
- 只有用户明确要求,或确有长期设计决策需要留档时,才新增/更新文档。
## 6. 汇报要求
用简洁对话汇报:完成内容、主要文件、关键设计选择、尚未解决的阻塞。除用户明确要求外,不生成长篇报告,不列出与本任务无关的测试证据。

17
Dockerfile 100644 → 100755
View File

@ -9,6 +9,19 @@
# 基础镜像。国内直连 docker.io 会在 load metadata 阶段 TLS 超时,所以支持指成本地已有的镜像:
# docker pull python:3.12-slim && docker build --build-arg BASE_IMAGE=python:3.12-slim .
# ./scripts/deploy.sh 会优先用本地已有的同名镜像,不会去联网试各种加速站。
# ---------- 阶段 1:前端构建(nex.config.yaml 标准栈:npm + Vite + React)----------
# 基础镜像同样可以指到本地已有的:docker build --build-arg NODE_IMAGE=node:22-alpine .
ARG NODE_IMAGE=node:22-alpine
FROM ${NODE_IMAGE} AS webbuild
ARG NPM_REGISTRY=https://registry.npmmirror.com
WORKDIR /web
# 依赖单独一层:只改业务代码时不重装 node_modules(国内直连 npmjs 慢时用 NPM_REGISTRY 换源)
COPY web/package.json web/package-lock.json ./
RUN npm ci --no-audit --no-fund --registry "${NPM_REGISTRY}"
COPY web ./
RUN npm run build # 产物在 /web/dist,由 FastAPI 挂在 /static 下托管
# ---------- 阶段 2:运行镜像 ----------
ARG BASE_IMAGE=python:3.12-slim
FROM ${BASE_IMAGE}
@ -35,8 +48,10 @@ RUN pip install --retries 5 --timeout 60 -i "$PIP_INDEX_URL" -r requirements.txt
# RUN pip install "pymysql>=1.1" "cryptography>=42.0"
COPY app ./app
COPY web ./web
COPY scripts ./scripts
# 运行镜像只要前端构建产物;web/legacy 是没构建时的兜底(app/main.py 里择优加载)
COPY --from=webbuild /web/dist ./web/dist
COPY web/legacy ./web/legacy
# 上传件 / 导出件目录;SQLite 库同样落在这里,实际内容由 volume 提供
RUN mkdir -p data/uploads data/exports

69
README.md 100644 → 100755
View File

@ -86,7 +86,18 @@ cd /path/to/unis_manager
打开 <http://127.0.0.1:8770>。服务默认监听 **0.0.0.0**:同事在局域网里用 `http://<本机IP>:8770` 直接访问(脚本启动时会把这行地址打印出来);只想本机访问就 `HOST=127.0.0.1 ./scripts/run.sh`。
首次运行 `scripts/run.sh` 会自动完成:检查 Python 3.10+ → 建项目内 `.venv` → 缺依赖自动安装(默认源失败会依次切国内镜像)→ 缺 `.env` 时从 `.env.example` 生成 → 建库 → 启动并打开浏览器。已有 `data/board.db` 时直接复用,不会覆盖数据。
首次运行 `scripts/run.sh` 会自动完成:检查 Python 3.10+ → 建项目内 `.venv` → 缺依赖自动安装(默认源失败会依次切国内镜像)→ **装前端依赖并构建 `web/dist`**(没有 node 时用 `web/legacy` 旧版兜底)→ 缺 `.env` 时从 `.env.example` 生成 → 建库 → 启动并打开浏览器。已有 `data/board.db` 时直接复用,不会覆盖数据。
**前端技术栈(`nex.config.yaml` 里的 nex-standard-fullstack)**:React 19 + TypeScript + Vite + Ant Design 6 + Tailwind CSS v4(只作工具类,颜色仍走 CSS Variables)+ Zustand + React Router 7 + Axios;源码在 `web/src/`。后端 FastAPI 只托管构建产物 `web/dist`(资源挂 `/static/`,深链回 `index.html`;没有 dist 时退回 `web/legacy` 的零构建旧版)。
| 前端命令 | 作用 |
|---|---|
| `cd web && npm install` | 装依赖(锁文件 `web/package-lock.json`,必须随仓库提交) |
| `cd web && npm run dev` | 5174 热更新开发,`/api` 代理到本地后端 |
| `cd web && npm run build` | `tsc --noEmit` + Vite 构建,产出 `web/dist` |
| `cd web && npm run typecheck` | 只做类型检查 |
`scripts/run.sh` 里对应:源文件比 `web/dist` 新就自动重建;`WEB=0` 跳过构建、`WEB=force` 强制重建、`NPM_REGISTRY=...` 换 npm 源。
### 启动方式与排错
@ -96,6 +107,7 @@ cd /path/to/unis_manager
| 报 `permission denied` | `chmod +x scripts/run.sh` 后重试(**不要用 sudo**) |
| 不想改权限 | `bash scripts/run.sh` |
| 缺 Python / 依赖 | 脚本自动安装;不想自动装就设 `AUTO_INSTALL=0`,脚本只打印命令 |
| 缺 Node / 前端构建失败 | 装 Node 20+ 再跑;只想先把服务跑起来可以 `WEB=0 ./scripts/run.sh`(界面用 `web/legacy` 旧版)|
| 换端口 | `PORT=8771 ./scripts/run.sh` |
| 关闭热加载 | `DEV=0 ./scripts/run.sh`(默认是开着的) |
| 不自动开浏览器 | `NO_OPEN=1 ./scripts/run.sh` |
@ -104,16 +116,16 @@ cd /path/to/unis_manager
> ⚠️ 不要用 `sudo` 启动:数据库文件会变成 root 属主,后续写入会失败。
> **热更新(默认开启)**:uvicorn 除 `*.py` 外还会监听 `web/**` 的 js/css/html 与 `.env`,改动即重启;
> 页面里的 `web/livereload.js` 每秒读一次 `/health` 的启动代际,发现服务重启后自动刷新浏览器。
> 也就是说改完代码**不用手动重启、也不用手动刷新**。`DEV=0 ./scripts/run.sh` 可关掉(关闭后该脚本首轮即自行停止)。
> `data/*.db` 的写入不会触发重启。
> **热更新(默认开启)**:uvicorn 监听 `app/**.py` 与 `.env`,改后端即重启。
> 改前端走另一条路:`cd web && npm run dev`(Vite 自带 HMR,`/api` 代理到后端),或改完 `npm run build` 再刷新——产物文件名带哈希,浏览器不会拿旧版。
> `DEV=0 ./scripts/run.sh` 关掉后端热重载;`data/*.db` 的写入不会触发重启。旧零构建版(`web/legacy/`)的 `livereload.js` 只在没有 `web/dist` 时生效。
### 手动分步执行(等价于 scripts/run.sh 干的事)
```bash
python3 -m venv .venv
./.venv/bin/pip install -r requirements.txt
cd web && npm ci && npm run build && cd .. # 前端产物 web/dist
./.venv/bin/python scripts/init_db.py
./.venv/bin/python -m uvicorn app.main:app --port 8770
```
@ -400,16 +412,27 @@ python scripts/legacy/add_entry_date.py --force # 全部重算
## 界面设计语言
前端是零构建的原生 JS(`web/index.html` + `web/styles.css` + `web/app.js` + `web/icons.js`),设计口径固定如下,新增页面请沿用:
前端是 Vite 构建的 React + TypeScript 应用(源码 `web/src/`,Ant Design 出控件、Tailwind v4 出工具类、项目 token 出一切视觉值)。设计口径固定如下,新增页面请沿用:
- **Token 只有一个来源**:颜色 / 圆角 / 阴影 / 间距 / 控件高度 / 层级 / 动效时长全部在 `web/src/styles/tokens.css` 顶部的 `:root`(`--text*`、`--surface-*`、`--primary*`、`--success/--warning/--danger`、`--radius-*`、`--sp-*`、`--ctrl-h-*`、`--z-*`、`--dur-*`)。组件里不再出现第二套 hex;业务数据色(项目分类色、阶段色)由 `web/src/domain/ink.ts` 的 `INK` 常量注入 `style={{ "--c": ... }}`,JS 模板里不写裸色值。文本对比度按 WCAG AA(≥4.5:1)取值。
- **tinted 底板只有一个算法**:`.pill` / `.tag-mini` / `.arch-badge` 只吃 `--c`,底色与文字色在 CSS 里用 `color-mix()` 派生;旧的「背景 hex + 文字 hex」成对写法已废,新增状态标签照 `--c` 办理。
- **弹层与焦点一条路**:一律用 AntD @B@Modal@B@ / @B@Drawer@B@(自带 @B@role="dialog"@B@、焦点陷阱、Escape 关闭、关闭后焦点归还触发元素),不再手写弹层与焦点栈;抽屉里再开弹窗由 AntD 的层级接管。图标按钮必须有 @B@aria-label@B@(@B@title@B@ 不算名字)。
- **新增 / 修改一律右侧侧滑**:表单类面板统一走 @B@components/FormDrawer.tsx@B@(头部 @B@.dlg-title@B@ + 可选副标题、正文 @B@.drawer-body@B@、底部固定「取消 + 保存/创建」右对齐、层内错误用行内 @B@Alert@B@、提交中按钮 loading 且不许 Esc 关闭);**删除等破坏性确认仍用 @B@modal.confirm@B@**(危险按钮 danger),不要为了统一把确认框也做成抽屉。窄屏 (<=640) 表单抽屉给全宽。
- **录入字段跟着「更新录入」走**:同一个对象在各模块里的表单字段与「更新录入」入口一致(自研:执行内容(正文,原文照录)/ 一句话摘要 / 总进度 / 整体状态 / 风险 / 阻塞 / 下一步计划;定制:执行内容 / 项目状态 / 开发进度(%)/ 本期新增计收(万元)/ 本期新增下单(万元)/ 一句话摘要 / 风险 / 阻塞 / 下一步计划)。模块特有的轴(自研的「子任务」)可以多不能少;措辞改了要四处一起改。
- **正文富文本一套约定**:「内容」这类正文支持加粗 / 下划线 / 斜体 / 语义色,用 `components/RichEditor.tsx`,内核是 **Tiptap 3(ProseMirror)**:回车分块、选区、中文输入法、撤销栈这几件事手写 contentEditable 反复出问题,交给成熟的编辑器内核。工具栏是我们自己排的(Tiptap 是 headless,样式跟着 NEX 走):**图标按钮** 加粗 / 斜体 / 下划线 + **颜色按钮(A + 当前色条 + ▾,弹出色板:只有色块不写中文,名称在 title / aria-label 里,第一个是「无色」= 摘色)** + 清除格式;图标进唯一图标层 `icons/paths.ts`(bold / italic / underline / eraser / chevron-down),不自建第二套图标。颜色是挂在自己写的 `data-c` 属性上的语义色 mark(**不用官方 Color,因为它存 hex,会脱离主题 token**),重复上色是替换语义;
产出只写 `<b>/<i>/<u>`(加粗斜体特意扩展成短标签,`<strong>/<em>` 只收不发);**回车 = 一行一段 `<p>`**(Shift+回车 = 行内 `<br>`),空行存 `<p><br></p>`——不带 `<br>` 的空段落在展示端没有行盒,编辑看得见、看着看不见就又不一致了;
三端换行口径统一:一个块级 = 一个换行(`utils/richtext.richToText` 用 DOM 走一遍,`app/export.py.plain()` 先把相邻 `</p><p>` 合成一个换行),别拿「开标签闭标签各断一次」那种写法,否则每行后面凭空多一个空行,展示一律 `components/RichText.tsx`(先消毒再注入);<b>项目里所有长文本录入都用这一个组件</b>(执行/交付记录正文、风险 / 阻塞、下一步计划、定制备注、重点工作说明与结果反馈、更新录入的原始内容与整理结果正文),单行字段(摘要、工作内容)保持普通输入框。<b>列表里的预览不要再按字数硬切</b>——那会把富文本压成纯文本,用户会以为格式没生效;改成 `<RichText className="clamp"/>` 两行截断,格式留着。存储就落在原来的 `content` 文本列里,只允许 `<b> <i> <u> <br> <span data-c="danger|warning|primary|success|muted">`;颜色存**语义名**不存 hex,渲染时映射回 `var(--*)` token,改主题会跟着变。要纯文本的地方(关键字匹配、截断、AI、Excel)走 `utils/richtext.ts` 的 `richToText` / 后端 `app/export.py` 的 `plain()`。「原始内容」粘贴框同样是富文本,但发给解析器 / AI 的那一份先转回纯文本——规则解析按行找「风险 / 下一步」,标记会打断它;入库的正文仍带标记。
- **状态不只靠颜色**:选中 / 按下 / 当前项写 `aria-current` / `aria-selected` / `aria-pressed`,CSS 用属性选择器出强调条与勾选图标;可排序表头是 `<th aria-sort>` + `.th-sort` 按钮,页签组是 `role="tablist"` + `.tabpanel`。
- **加载与忙态统一**:列表 / 卡片占位用 AntD `Skeleton`(`<TableSkeleton/>` / `<CardSkeleton/>`,不写「加载中…」文本),取数一律 `useAsync()`(自带竞态守卫 + `loading` / `error`);耗时动作 `loading` / `disabled` + `aria-busy`,导出走 `download(url, btn, message)`;结果只经 `message`(AntD App 上下文,`role="status"`),表单错误槽是 `<Alert role="alert">`。
- **断点登记在 CSS 顶部注释**:1180(周看板转单栏)/ 1100(侧栏转抽屉)/ 900(顶栏换行、抽屉全宽)/ 780(表单与人员卡换行)/ 640(触控尺寸、弹窗转底部抽屉)。CSS 不能在 `@media` 里用 `var()`,改断点必须同步那条注释。动效一律 ≤280ms 且尊重 `prefers-reduced-motion`;`forced-colors` 下兜底焦点环。
- **禁用「彩色描边」**:卡片、列表、步骤条、表格一律中性灰边框(`--border` / `--border-strong`)或无边框,不用圆角多色边框表达状态。
- **重点色只出现在三处**:图标、关键数字/文本、小面积 tinted 底板(`.ic-badge`、`.tag-mini`、`.kpi.accent-*`)。状态色(`statusMeta`)与阶段色(`stageMeta`)是唯一配色来源,避免各页面自己调色。
- **图标系统**:`web/icons.js` 内置 48 个 24×24 线性 SVG(每个都被界面或状态/阶段/标题映射引用,死图标随手删),`stroke=currentColor`,颜色跟着文字走。对外 API:
`svg(name)` 裸图标;`badge(name)` 图标 + tinted 底板(KPI 用);`status()` / `stage()` / `pipe()` 按状态·阶段·交付环节取图标;
`nameOfStatus()` / `nameOfStage()` / `statusBadge()` 出文案与徽标;`hydrate()` 填 `[data-icon]`;`auto()` 自动补前导图标。
- **自动图标**:`auto()` + `MutationObserver` 在每次渲染后按标题关键词给 `.card-head h4` / `.sec-title` / `.wk-group-head` / `.notice` / `.empty` 加前导图标,并填充 `[data-icon]`;用 `data-ico` 属性防重复,标题里**自带** `<svg class="ic">`(如阶段看板按阶段取图标)时跳过自动补图,不会出现两个图标。新增区块只要标题里带对应关键词就自动带图标,不用手写。
- **图标系统**:`web/src/icons/` 内置 52 个 24×24 线性 SVG(每个都被界面或状态/阶段/标题映射引用,死图标随手删),`stroke=currentColor`,颜色跟着文字走。对外 API:
`<Icon name="wallet" />` 裸图标;`<IconBadge />` 图标 + tinted 底板(KPI 用);`<StatusIcon/>` / `<StageIcon/>` / `<PipeIcon/>` 按状态·阶段·交付环节取图标;
`nameOfStatus()` / `nameOfStage()` / `nameOfPipe()` 出图标名;`iconForTitle()` / `iconForEmpty()` 按关键词挑图标。
- **自动图标**:`iconForTitle()` 在渲染期按标题关键词给 `<PanelCard title>` / `<SectionTitle>` 补前导图标(旧版是 `MutationObserver` 全局扫 DOM,现在组件自己算,没有副作用);标题里**自带** `<Icon />` 时不再补第二个。
- **交付环节图标按 `code` 取**:后端 `CUSTOM_PIPELINE` 下发的字段是 **`code`**(不是 `key`),前端一律 `Ico.pipe(s.code)`;写成 `s.key` 会静默退化成通用圆点。
- **表格防竖排**:`table.tbl th` / `.pill` / `.tag-mini` 统一 `white-space:nowrap`,容易挤窄的列(区域、负责人)在 `<td>` 上加 `class="nowrap"`;实在挤不下交给 `.tbl-wrap { overflow:auto }` 横向滚动。
- **表格防竖排**:标签(`.pill` / `.tag-mini`)与列头一律 `white-space:nowrap`,容易挤窄的列(区域、负责人)在 `columns` 上加 `className: "nowrap"`;宽表交给 AntD Table 的 `scroll={{ x }}` 横向滚动 + 操作列 `fixed: "right"`,不给它换行挤成一竖。
- **抽屉不被内容撑破**:`.form-row > div { min-width: 0 }`(grid 子项默认 `min-width:auto`,会被交付环节步骤条撑出整表横向滚动),步骤条本身 `flex:1 1 132px`(132px = 日期输入框含日历图标的最小可用宽度)。
- **报错一律中文**:Pydantic 422 与未捕获 500 在 `app/main.py` 的 exception handler 统一换成中文 `detail`(「提交的数据有误:…」/「服务器内部错误…」),前端 `api()` 原样 toast,界面不中英夹杂。新增 `/export/*` 必须登记 `security.EXPORT_MENU` 权限归属,未登记一律 403(fail-closed,防「忘挂权限 = 登录即可下载」)。
- **反馈矩阵(只有这三条通道)**:弹窗内报错 → `modalError()`(`#mErr` 行内提示);抽屉表单报错 → `formError("fdErr|cdErr|dwErr", msg)`(行内提示,传空串清除);其余一律 `toast()`;破坏性动作只走 `confirmDialog()`。异步写处理器先本地 try/catch 提示并**中断后续刷新/重开**,全局 `unhandledrejection` 兜底只兜漏网之鱼。
@ -543,7 +566,7 @@ AuditLog(用户, 动作 create|update|delete|login|logout|deny, 菜单, 方法,
```bash
./.venv/bin/pip install -r requirements-dev.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
./.venv/bin/python -m pytest # 102 个用例,几秒钟跑完
./.venv/bin/python -m pytest # 103 个用例,几秒钟跑完
```
- 测试跑在临时库里:`tests/conftest.py` 在 import 业务模块之前就把 `DATABASE_URL` 指向临时文件,**不会碰 `data/board.db`**。
@ -551,6 +574,8 @@ AuditLog(用户, 动作 create|update|delete|login|logout|deny, 菜单, 方法,
AI 相关用例走确定性的本地规则解析,不联网。
- 覆盖范围:登录 / 口令 / 会话限流、RBAC 授权矩阵与越权与审计、周期与项目与执行记录、
定制项目财务口径(跨季度、跨年回归)、年度目标、花名册 / 每周重点 / 工作看板、AI 整理与六类 Excel 导出。
- 还有一道静态防线:`tests/test_api_contract.py::test_前端查询参数必须在后端有声明` 扫描 `web/src/api/endpoints.ts`,
前端发出的每个查询键 / body 键都必须在后端 OpenAPI 里声明过(旧版抓到过「前端一直发、后端一直丢」的整类 bug)。
## 迁移到 MySQL
@ -579,7 +604,23 @@ app/
ai_parser.py LLM 解析 + 本地规则兜底(通用 / 定制两套)
routers/ auth · rbac(角色/账号/会话/审计) · board(周期/元数据) · weekly(看板数据) ·
projects · custom(定制项目 + 财务) · focus · staff · ai · export
web/ index.html · styles.css · app.js · icons.js(零依赖,无构建步骤)
web/ 前端(nex.config.yaml 标准栈:React + TypeScript + Vite + Ant Design +
Tailwind v4 + Zustand + React Router + Axios)
src/
main.tsx App.tsx router.tsx 入口 / 会话门 / 八个视图的懒加载路由
api/ client.ts(Axios:401 广播、中文错误、导出走 blob+下载)
endpoints.ts(一接口一函数,查询键集中在这一层,测试据此对表)
store/ session.ts(登录态与 canR/canW)· meta.ts(字典/周期/台账缓存 + dataRev)
ui.ts(界面状态,sessionStorage 键 unis.ui.v2,字段与旧版一致)
components/ Shell(侧栏/顶栏/用户胶囊)· PageHead · PanelCard · KpiCard · DataState ·
PagerBar · Trunc · PeriodPicker · LoginGate · ProfileModal · UserChip
domain/ ink.ts(界面色只引用 token)· pills.tsx(状态标签:一个 --c 派生底色)
icons/ 唯一图标层:SVG 路径表 + <Icon/> / <IconBadge/>(AntD 自带图标不参与业务用图)
styles/ tokens.css(设计 token 唯一来源 + Tailwind @theme)· app.css(结构层)
views/ board · projects · custom · focus · staff · intake · settings · rbac
index.html · vite.config.ts · tsconfig.json · package.json · package-lock.json
dist/ Vite 构建产物(不入库,由 FastAPI 挂在 / 与 /static 下)
legacy/ 改造前的零构建版(app.js · styles.css · icons.js · index.html),没有 dist 时兜底
tests/ pytest 接口测试(conftest 用临时库,绝不碰 data/board.db)
scripts/
run.sh 本地启动:Python / venv / 依赖 / .env / 建库自动兜底
@ -591,7 +632,7 @@ scripts/
legacy/ 一次性历史修数脚本(shift_year · merge_project · migrate_custom ·
add_entry_date · fix_period_split),不参与启动流程
data/board.db SQLite 数据库
Dockerfile 运行镜像(依赖 + 代码,启动时自动补表/预置分类)
Dockerfile 两阶段镜像:node:22 构建 web/dist → python:3.12 运行(启动时自动补表/预置分类)
docker-compose.yml 部署编排(./data 持久化、HOST_PORT、健康检查)
.dockerignore 排除 data/ 与 .env,不把数据和密钥打进镜像
```

5
a.jar
View File

@ -1,5 +0,0 @@
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_127.0.0.1 FALSE / FALSE 1796319979 unis_session HUHK9RCf7c5jvaXYqZp1Ztk0ajFpl5OYW9dK3npuVkM

0
app/__init__.py 100644 → 100755
View File

0
app/ai_parser.py 100644 → 100755
View File

0
app/audit.py 100644 → 100755
View File

0
app/config.py 100644 → 100755
View File

0
app/constants.py 100644 → 100755
View File

0
app/db.py 100644 → 100755
View File

31
app/export.py 100644 → 100755
View File

@ -4,6 +4,8 @@
"""
from __future__ import annotations
import re
from datetime import datetime
from io import BytesIO
from typing import Any, Iterable, Sequence
@ -21,6 +23,33 @@ BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
NUM_FMT = "#,##0.00"
# 正文支持简单富文本(加粗 / 下划线 / 斜体 / 语义色,前后端约定见 web/src/utils/richtext.ts)。
# Excel 不认这套标记,出表前统一降级成纯文本:换行标记变成真换行,其余标签剥掉、实体还原。
# 只在我们自己的标签出现时才动手,项目名里带个尖括号不会被误伤。
RICH_TAG = re.compile(r"</?(?:b|i|u|br|p|div|span)\b[^>]{0,60}?>", re.I)
_BREAK_TAG = re.compile(r"<br\s*/?>|</(?:p|div)>", re.I)
_ADJACENT_BLOCK = re.compile(r"</(?:p|div)>\s*<(?:p|div)\b[^>]{0,60}?>", re.I)
_ENTITIES = {"&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&#39;": "'", "&nbsp;": " "}
def plain(value: Any) -> Any:
"""富文本 → 纯文本;不是字符串或不含标记时原样返回。
换行口径和前端 utils/richtext.richToText 保持一致:相邻段落之间只算一个换行
(编辑器产出 <p>一行</p><p>一行</p>,开闭标签各断一次行会凭空多出空行),
块开头也断行是为了兼容早年 Chrome 留下的「裸文本 + <div>」这种混排。
"""
if not isinstance(value, str) or not RICH_TAG.search(value):
return value
s = _ADJACENT_BLOCK.sub("\n", value)
s = _BREAK_TAG.sub("\n", s)
s = re.sub(r"<(?:p|div)\b[^>]{0,60}?>", "\n", s, flags=re.I)
s = re.sub(r"<[^>]{0,80}?>", "", s)
for k, v in _ENTITIES.items():
s = s.replace(k, v)
return re.sub(r"\n{3,}", "\n\n", s).strip()
def _cell_width(value: Any) -> int:
"""按中文字符占 2 个宽度估算显示宽度。"""
s = "" if value is None else str(value)
@ -64,7 +93,7 @@ def build_xlsx(
for r, row in enumerate(rows, head_row + 1):
for c, v in enumerate(row, 1):
cell = ws.cell(row=r, column=c, value=v)
cell = ws.cell(row=r, column=c, value=plain(v)) # 富文本降级成纯文本再入表
cell.border = BORDER
cell.alignment = Alignment(vertical="top", wrap_text=False)
if c in money_cols and isinstance(v, (int, float)):

0
app/finance.py 100644 → 100755
View File

24
app/main.py 100644 → 100755
View File

@ -77,16 +77,21 @@ api.include_router(auth.router, prefix="", tags=["auth"])
api.include_router(rbac.router, prefix="", tags=["rbac"])
app.mount("/api", api)
# 前端是 Vite 构建产物(web/src → web/dist,栈见 nex.config.yaml:React + TS + AntD + Tailwind v4)。
# 没构建时退回 web/legacy(改造前的零构建版),本地与容器里都不会白屏。
# 构建资源以 /static/ 为 base(见 web/vite.config.ts),所以静态目录整个挂到 /static。
WEB_DIR = config.BASE_DIR / "web"
app.mount("/static", StaticFiles(directory=str(WEB_DIR)), name="static")
DIST_DIR = WEB_DIR / "dist"
STATIC_DIR = DIST_DIR if (DIST_DIR / "index.html").is_file() else WEB_DIR / "legacy"
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# 前端零构建、文件名不带版本号,浏览器会启发式缓存 index.html / app.js / styles.css,
# 改完界面看不到新版。no-cache 不做新鲜度缓存、只带 ETag 回源校验(未变更时返回 304)。
# index.html 不能启发式缓存(它指向的产物文件名带哈希,只有 index.html 会变),
# no-cache 不做新鲜度缓存、只带 ETag 回源校验(未变更时返回 304)。
@app.middleware("http")
async def no_cache_frontend(request, call_next):
response = await call_next(request)
if request.url.path == "/" or request.url.path.startswith("/static/"):
if request.url.path == "/" or request.url.path.startswith("/static/"): # 产物文件名带哈希,index.html 才是不缓存的关键
response.headers["Cache-Control"] = "no-cache"
return response
@ -103,4 +108,13 @@ def health():
@app.get("/")
def index():
return FileResponse(str(WEB_DIR / "index.html"))
return FileResponse(str(STATIC_DIR / "index.html"))
@app.get("/{path:path}")
def spa(path: str):
"""单页应用深链:/custom、/settings/… 这类路径没有实体文件,一律交回 index.html 由前端路由。
带扩展名的请求(.js/.css/.svg…)已经由各 mount 接走,落到这里就是 404,不要假装修上了。"""
if "." in path.rsplit("/", 1)[-1]:
return JSONResponse({"detail": "没有这个资源"}, status_code=404)
return FileResponse(str(STATIC_DIR / "index.html"))

0
app/models.py 100644 → 100755
View File

0
app/routers/__init__.py 100644 → 100755
View File

0
app/routers/ai.py 100644 → 100755
View File

0
app/routers/auth.py 100644 → 100755
View File

0
app/routers/board.py 100644 → 100755
View File

0
app/routers/custom.py 100644 → 100755
View File

20
app/routers/export.py 100644 → 100755
View File

@ -17,7 +17,7 @@ from sqlalchemy.orm import Session
from .. import finance
from ..constants import CUSTOM_STAGE_MAP, STATUS_MAP
from ..db import get_db
from ..export import build_xlsx, xlsx_response
from ..export import build_xlsx, plain, xlsx_response
from ..models import (
CustomProject,
CustomUpdate,
@ -140,7 +140,7 @@ def export_custom_updates(
ups = q.order_by(CustomUpdate.period_id, CustomUpdate.custom_project_id).all()
if keyword:
kw = keyword.strip()
ups = [u for u in ups if kw in (u.content or "") or kw in (u.summary or "")
ups = [u for u in ups if kw in plain(u.content or "") or kw in plain(u.summary or "")
or kw in (u.project.name if u.project else "")
or kw in (u.project.customer if u.project else "")]
@ -157,7 +157,7 @@ def export_custom_updates(
cp.name if cp else "",
(cp.region or "") if cp else "",
_stage_name(u.stage),
(u.content or "").replace("\n", " ")[:500],
plain(u.content or "").replace("\n", " ")[:500],
u.progress,
u.amount_delta,
u.revenue_delta,
@ -268,7 +268,7 @@ def export_updates(
if keyword:
# 看板工具栏的搜索框会带着它来导出:内容 / 摘要 / 子任务 / 项目名任一命中
kw = keyword.strip()
ups = [u for u in ups if kw in (u.content or "") or kw in (u.summary or "")
ups = [u for u in ups if kw in plain(u.content or "") or kw in plain(u.summary or "")
or kw in (u.task.name if u.task else "") or kw in (u.project.name if u.project else "")]
headers = [
"周期", "项目", "子任务", "执行情况", "进度(%)", "状态", "风险", "下一步", "来源",
@ -280,7 +280,7 @@ def export_updates(
u.period.to_dict()["full_label"] if u.period else "",
u.project.name if u.project else "",
u.task.name if u.task else "",
(u.content or "").replace("\n", " ")[:500],
plain(u.content or "").replace("\n", " ")[:500],
u.progress,
STATUS_MAP.get(u.status, (u.status,))[0],
(u.risk or "").replace("\n", " ")[:200],
@ -371,13 +371,15 @@ def export_focus(
q = q.filter(WeeklyFocus.archived.is_(True))
if status:
q = q.filter(WeeklyFocus.status == status)
if keyword:
q = q.filter(WeeklyFocus.content.contains(keyword) | WeeklyFocus.detail.contains(keyword))
periods = {p.id: p for p in db.query(Period).all()}
items = sorted(
q.all(),
key=lambda f: (-(periods[f.period_id].sort_key if f.period_id in periods else 0), -f.id),
)
if keyword:
# 说明可能存的是富文本 HTML,子串匹配要在纯文本上做(重点工作量小,排序后再筛即可)
kw = keyword.strip()
items = [f for f in items if kw in (f.content or "") or kw in plain(f.detail or "")]
headers = ["序号", "工作内容", "说明", "预计完成时间", "录入周", "执行状态", "是否延期", "结果反馈", "更新"]
rows = []
@ -387,12 +389,12 @@ def export_focus(
[
i,
f.content,
(f.detail or "").replace("\n", " "),
plain(f.detail or "").replace("\n", " "), # 说明支持简单富文本,出表降级成纯文本
f.due_date or "",
period.to_dict()["full_label"] if period else "",
STATUS_MAP.get(f.status, (f.status,))[0],
"是" if f.delayed else "",
(f.result or "").replace("\n", " "),
plain(f.result or "").replace("\n", " "),
f.updated_at.strftime("%Y-%m-%d %H:%M") if f.updated_at else "",
]
)

0
app/routers/focus.py 100644 → 100755
View File

0
app/routers/projects.py 100644 → 100755
View File

0
app/routers/rbac.py 100644 → 100755
View File

0
app/routers/staff.py 100644 → 100755
View File

4
app/routers/weekly.py 100644 → 100755
View File

@ -137,8 +137,8 @@ def weekly(
continue
entry = (cp.entry_date or "").strip()
is_new = bool(scope_start and scope_end and entry and scope_start <= entry <= scope_end)
# 「本周新增 / 本周验收」与「定制项目 · 本周进展」同一口径(见 web/app.js 的
# customWeeklySections):新增按「下单时间」,验收按「更新时间 + 状态=已验收」。
# 「本周新增 / 本周验收」与「定制项目 · 本周进展」同一口径(见 web/src/views/CustomView.tsx 的「本周进展」与
# web/src/views/BoardView.tsx 的定制动态汇总):新增按「下单时间」,验收按「更新时间 + 状态=已验收」。
sign = (cp.sign_date or "").strip()[:10]
upd = (cp.update_date or "").strip()[:10]
is_signed_new = bool(scope_start and scope_end and sign and scope_start <= sign <= scope_end)

0
app/schema_patch.py 100644 → 100755
View File

0
app/schemas.py 100644 → 100755
View File

0
app/security.py 100644 → 100755
View File

480
d.js
View File

@ -1,480 +0,0 @@
window.__ModuleLoader__.load({
id: "@deepseek-ai/dsh-api-workspace-files",
factory: (require) => {
var module = { exports: {} };
var exports = module.exports;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
require("@deepseek-ai/cordis");
//#region lib/types/client/change-feed.js
/**
* The follower key of one absolute path.
* @param path - an absolute path from a Host stat or change frame.
* @returns the path with `\\` normalized to `/`.
*/
function keyOf(path) {
return path.replace(/\\/g, "/");
}
/** Notices of one follower, delivered in order and pulled by its consumer. */
var Follower = class {
leave;
pending = [];
started = Promise.withResolvers();
wake;
ended = false;
hostKey;
/**
* Resolves true after the Host acknowledges its subscription, or false if
* this follower ends before acknowledgement.
*/
ready = this.started.promise;
/**
* @param leave - unregisters this follower and its abort listener.
*/
constructor(leave) {
this.leave = leave;
}
/**
* Select the Host path for queued and future changes.
* @param absolutePath - the successful stat's absolute path.
*/
bind(absolutePath) {
this.hostKey = keyOf(absolutePath);
}
/** The Host acknowledged an active subscription and resolved workspace root. */
start() {
this.started.resolve(true);
}
/**
* Queue one notice.
* @param notice - what the consumer receives next.
* @param key - normalized Host path for the change.
*/
push(notice, key) {
this.pending.push({
key,
notice
});
this.wake?.();
}
/** Deliver what is queued, then finish. */
end() {
this.ended = true;
this.started.resolve(false);
this.wake?.();
}
/** Unregister even when the consumer has not started pulling notices. */
dispose() {
this.leave();
}
/** @inheritdoc */
async *[Symbol.asyncIterator]() {
try {
while (true) {
const next = this.pending.shift();
if (next !== void 0) {
if (next.notice.kind === "refresh" || this.hostKey === void 0 || next.key === this.hostKey) yield next.notice;
continue;
}
if (this.ended) return;
await new Promise((resolve) => {
this.wake = resolve;
});
this.wake = void 0;
}
} finally {
this.dispose();
}
}
};
/** The stream and followers of one Session and requested path. */
var SessionFeed = class {
onClose;
followers = /* @__PURE__ */ new Set();
stream;
closed = false;
started = false;
acknowledged = false;
/**
* @param remote - the Remote face carrying `workspaceFiles.changes`.
* @param sessionId - the Session whose filesystem this feed observes.
* @param path - target path submitted to the Host.
* @param after - the previous feed of this target still closing, if any; the stream opens once it has settled.
* @param onClose - called once when the stream is gone, whatever the cause, with the dispose that is closing it.
*/
constructor(remote, sessionId, path, after, onClose) {
this.onClose = onClose;
this.stream = remote.$stream({
name: `workspace file changes of ${sessionId}`,
open: (signal) => {
this.started = false;
return openAfter(after, () => remote.workspaceFiles.changes(sessionId, path, signal));
},
ended: () => /* @__PURE__ */ new Error(`workspace file changes of ${sessionId} ended`)
});
this.pump();
}
/**
* Register one resource address before its Host path is known.
* @param follower - receives changes and binds its path after stat.
*/
add(follower) {
this.followers.add(follower);
if (this.started) follower.start();
}
/**
* Unregister one follower; the last one leaving disposes the stream.
* @param follower - the follower to drop.
*/
remove(follower) {
this.followers.delete(follower);
if (this.followers.size === 0) this.close();
}
async pump() {
try {
for await (const item of this.stream) {
const frame = item.value;
switch (frame.kind) {
case "ready":
item.accept();
this.started = true;
for (const follower of this.followers) {
follower.start();
if (this.acknowledged) follower.push({ kind: "refresh" }, "");
}
this.acknowledged = true;
break;
case "change": {
const key = keyOf(frame.change.absolutePath);
const notice = editOf(frame.change);
for (const follower of this.followers) follower.push(notice, key);
break;
}
default: assertNever(frame);
}
}
} catch {} finally {
this.close();
}
}
close() {
if (this.closed) return;
this.closed = true;
const closed = this.stream.dispose();
for (const follower of this.followers) follower.end();
this.followers.clear();
this.onClose(closed);
}
};
/**
* Open a Host stream once a predecessor has finished closing.
* @param after - the predecessor's dispose, or nothing to wait for.
* @param open - opens the stream.
* @returns the stream's items.
*/
async function* openAfter(after, open) {
await after;
yield* open();
}
/**
* The write one Host frame reports.
* @param frame - the Host frame.
* @returns the edit notice followers receive.
*/
function editOf(frame) {
return "absent" in frame ? { kind: "absent" } : {
kind: "changed",
version: frame.version
};
}
function assertNever(frame) {
throw new Error(`Unexpected workspace file watch frame: ${JSON.stringify(frame)}`);
}
/**
* Per-target sharing of the Host's workspace file change streams.
*
* Owned by the provider; one instance serves every session of the Client.
*/
var ChangeFeed = class {
remote;
/** Live feeds only: a feed removes itself when its stream closes. */
sessions = /* @__PURE__ */ new Map();
/** Streams still closing, by Session and path; a successor waits for its predecessor. */
closing = /* @__PURE__ */ new Map();
/**
* @param remote - the Remote face carrying `$stream` and `workspaceFiles.changes`.
*/
constructor(remote) {
this.remote = remote;
}
/**
* Follow one resource in one session before its Host path is known.
*
* The follower is registered on call, not on first pull. Changes delivered
* to this Client are queued while stat is pending. The first follower starts
* target's local `changes` call. The iterable ends
* when `signal` aborts or when the target stream is gone; ending it early
* (`break`, `return`) unregisters the follower as well, and the last follower
* of a target disposes its stream. Await a true `ready` result before stat
* so the Host subscription is active, then bind each stat's absolute path. Until binding,
* any target invalidation can trigger a retry; after binding, only matching queued
* and live changes pass.
* @param sessionId - the Session providing the file's read authority.
* @param path - requested file path; followers share a stream only for the same Session and path.
* @param signal - ends the follow.
* @returns a single-consumer subscription with Host-path binding and explicit disposal.
*/
follow(sessionId, path, signal) {
const feed = signal.aborted ? void 0 : this.feedOf(sessionId, path);
const leave = () => {
signal.removeEventListener("abort", leave);
follower.end();
feed?.remove(follower);
};
const follower = new Follower(leave);
if (feed === void 0) follower.end();
else {
feed.add(follower);
signal.addEventListener("abort", leave, { once: true });
}
return follower;
}
/**
* Wait for every stream that is still closing, so an owner tearing down
* leaves no Host stream behind.
* @returns resolves once no stream of this feed is closing.
*/
async settle() {
await Promise.all(this.closing.values());
}
feedOf(sessionId, path) {
const key = JSON.stringify([sessionId, path]);
const existing = this.sessions.get(key);
if (existing !== void 0) return existing;
const feed = new SessionFeed(this.remote, sessionId, path, this.closing.get(key), (closed) => {
this.sessions.delete(key);
const tracked = closed.then(() => void 0, () => void 0).then(() => {
if (this.closing.get(key) === tracked) this.closing.delete(key);
});
this.closing.set(key, tracked);
});
this.sessions.set(key, feed);
return feed;
}
};
//#endregion
//#region ../../typert/protocol/lib/index.js
/** The one Remote failure class shared by owners, the Gateway, and consumers. */
/**
* One Remote call failure: a real Error carrying its stable code and typed
* details. Owners throw it at the failure point; the Host Gateway encodes it
* onto the wire unchanged; the Client face rebuilds an instance for the
* `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
* Discrimination is always by `code`, never by instanceof.
*/
var RemoteError = class extends Error {
code;
details;
/** Structural marker: cross-realm/bundle identification never uses instanceof. */
isDSHRemoteError = true;
/**
* @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
* @param message - human diagnostic carried across the wire.
* @param details - structured payload typed by the code.
* @param options - standard Error options (`cause` survives in-process only).
*/
constructor(code, message, details, options) {
super(message, options);
this.code = code;
this.details = details;
this.name = "RemoteError";
}
};
//#endregion
//#region ../../util/workspace-path/lib/index.js
/**
* The `dsh-resource://file/…` address grammar: how a file is named across the
* Sidebar and the resource model, built and parsed without touching a
* filesystem.
* @module
*/
/** The scheme and type every file address opens with. */
const FILE_ADDRESS_PREFIX = "dsh-resource://file/";
/** Whether a decoded first path segment is a Windows drive (`C:`). */
function isDriveSegment(segment) {
return segment !== void 0 && /^[A-Za-z]:$/.test(segment);
}
/**
* Read a file address back into its parts without resolving `.` or `..`.
* Query and fragment suffixes are ignored; encoded path segments are decoded.
* @param address - a candidate address.
* @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded.
*/
function parseFileAddress(address) {
try {
if (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0;
const end = address.search(/[?#]/);
const [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split("/");
if (scope === "session") {
const [id, ...segments] = rest;
if (id === void 0 || id === "" || segments.length === 0) return void 0;
return {
scope,
sessionId: decodeURIComponent(id),
path: segments.map(decodeURIComponent).join("/")
};
}
if (scope === "absolute") {
const unc = rest[0] === "" && rest.length > 1;
const segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent);
if (segments.length === 0 || segments[0] === "") return void 0;
if (unc) return {
scope,
path: `//${segments.join("/")}`
};
return {
scope,
path: isDriveSegment(segments[0]) ? segments.join("/") : `/${segments.join("/")}`
};
}
return;
} catch {
return;
}
}
//#endregion
//#region lib/types/client/provider.js
/**
* Build the `file` provider over one Remote face and one change feed.
* @param remote - the Remote face carrying `workspaceFiles.stat`.
* @param changes - target-scoped change streams shared by file resources.
* @returns the provider to register into `ctx.resources`.
*/
function createFileResourceProvider(remote, changes) {
return {
protocol: "file",
async *open(address, { signal }) {
const resolved = resolve(address);
if (!resolved.ok) {
yield resolved;
return;
}
const { sessionId, path } = resolved.value;
const notices = changes.follow(sessionId, path, signal);
const stat = () => remote.workspaceFiles.stat(sessionId, path, signal);
const aborted = () => signal.aborted;
let current;
try {
if (!await notices.ready) {
if (aborted()) return;
const result = await stat();
if (!aborted()) yield result;
return;
}
if (aborted()) return;
const first = await stat();
if (aborted()) return;
if (first.ok) {
notices.bind(first.value.absolutePath);
current = first.value;
yield {
ok: true,
value: current
};
} else yield first;
for await (const notice of notices) {
if (aborted()) return;
if (current === void 0) {
if (notice.kind === "absent") continue;
} else if (notice.kind === "changed") {
if (notice.version === current.version) continue;
}
const again = await stat();
if (aborted()) return;
if (!again.ok) {
current = void 0;
yield again;
continue;
}
notices.bind(again.value.absolutePath);
current = again.value;
yield {
ok: true,
value: current
};
}
} finally {
notices.dispose();
}
}
};
}
/**
* Resolve one address to the Host call it stands for, or to the failure frame it earns.
* @param address - the full address, scheme included.
* @returns the Host file, or the `unsupported-address` / `unknown-workspace` failure.
*/
function resolve(address) {
const parsed = parseFileAddress(address);
if (parsed === void 0) return {
ok: false,
error: unsupportedAddress(address)
};
if (parsed.scope === "session") return {
ok: true,
value: {
sessionId: parsed.sessionId,
path: parsed.path
}
};
return {
ok: false,
error: unknownWorkspace(address)
};
}
/**
* The failure frame's error for an address this provider does not serve.
* @param address - the offending address.
* @returns the typed error.
*/
function unsupportedAddress(address) {
return new RemoteError("workspace-file/unsupported-address", `${address} is not a dsh-resource://file/session/<sessionId>/<path> or dsh-resource://file/absolute/<path> address`, { address });
}
/**
* The failure frame's error for an absolute address with no Session.
* @param address - the offending address.
* @returns the typed error.
*/
function unknownWorkspace(address) {
return new RemoteError("workspace-file/unknown-workspace", `${address} requires a dsh-resource://file/session/<sessionId>/<path> address`, { address });
}
//#endregion
//#region lib/types/client/index.js
/** Required browser services: the resource model, the Remote carrier and its namespace. */
const inject = [
"resources",
"remote",
"remote.workspaceFiles"
];
/**
* Client plugin body: register the `file` provider for this plugin's lifetime.
* @param ctx - client root context carrying `resources` and the Remote face.
*/
function apply(ctx) {
const changes = new ChangeFeed(ctx.remote);
const provider = createFileResourceProvider(ctx.remote, changes);
ctx.effect(() => {
const release = ctx.resources.register(provider);
return async () => {
release();
await changes.settle();
};
}, "workspace-files: file resource provider");
}
//#endregion
exports.apply = apply;
exports.inject = inject;
return module.exports;
}
});
;
//# sourceMappingURL=??@deepseek-ai/dsh-api-workspace-files/client.js.map&rev=6c462da1fc74

0
docker-compose.yml 100644 → 100755
View File

1
info
View File

@ -1 +0,0 @@
loglevel-

65
nex.config.yaml 100755
View File

@ -0,0 +1,65 @@
# NEX 0.1.7 默认项目配置
# 新项目使用明确默认栈;已有项目保留真实栈。
# 普通使用无需填写整张表,只需覆盖与项目意图不同的字段。
nex:
version: "0.1.7"
compliance: required
project:
name: auto
lifecycle: auto # auto | new | existing
type: fullstack # fullstack | frontend-only | backend-only
language: zh-CN
# 仅作为新项目的默认技术方案。已有项目不得据此迁移。
stack:
preset: nex-standard-fullstack
version_policy: latest-stable-compatible
lockfile: required
frontend:
framework: React
language: TypeScript
build_tool: Vite
package_manager: npm
ui_library: Ant Design
styling: Tailwind CSS v4 + CSS Variables
state_management: Zustand
routing: React Router
http_client: Axios
backend:
language: Python
framework: FastAPI
validation: Pydantic
orm: SQLAlchemy
migrations: Alembic
database:
development: SQLite
production: PostgreSQL
api:
style: REST
contract: OpenAPI
storage:
local_assets: ./data
# NEX 只定义设计和开发行为,不定义测试工具或质量闸门。
requirements:
use_shared_components: true
use_design_tokens: true
maintain_existing_interactions: true
preserve_verified_patterns: true
preserve_existing_stack: true
avoid_duplicate_design_system_layers: true
responsive_design: required
accessibility_design: required
performance_aware_design: required
audit_before_broad_refactor: true
require_approval_for_broad_changes: true
agent:
default_execution: lightweight
load_documents_by_task: true
create_reports_by_default: false
create_custom_check_scripts: false
add_test_frameworks: false
run_full_project_audit_for_routine_tasks: false

480
p.js
View File

@ -1,480 +0,0 @@
window.__ModuleLoader__.load({
id: "@deepseek-ai/dsh-api-workspace-files",
factory: (require) => {
var module = { exports: {} };
var exports = module.exports;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
require("@deepseek-ai/cordis");
//#region lib/types/client/change-feed.js
/**
* The follower key of one absolute path.
* @param path - an absolute path from a Host stat or change frame.
* @returns the path with `\\` normalized to `/`.
*/
function keyOf(path) {
return path.replace(/\\/g, "/");
}
/** Notices of one follower, delivered in order and pulled by its consumer. */
var Follower = class {
leave;
pending = [];
started = Promise.withResolvers();
wake;
ended = false;
hostKey;
/**
* Resolves true after the Host acknowledges its subscription, or false if
* this follower ends before acknowledgement.
*/
ready = this.started.promise;
/**
* @param leave - unregisters this follower and its abort listener.
*/
constructor(leave) {
this.leave = leave;
}
/**
* Select the Host path for queued and future changes.
* @param absolutePath - the successful stat's absolute path.
*/
bind(absolutePath) {
this.hostKey = keyOf(absolutePath);
}
/** The Host acknowledged an active subscription and resolved workspace root. */
start() {
this.started.resolve(true);
}
/**
* Queue one notice.
* @param notice - what the consumer receives next.
* @param key - normalized Host path for the change.
*/
push(notice, key) {
this.pending.push({
key,
notice
});
this.wake?.();
}
/** Deliver what is queued, then finish. */
end() {
this.ended = true;
this.started.resolve(false);
this.wake?.();
}
/** Unregister even when the consumer has not started pulling notices. */
dispose() {
this.leave();
}
/** @inheritdoc */
async *[Symbol.asyncIterator]() {
try {
while (true) {
const next = this.pending.shift();
if (next !== void 0) {
if (next.notice.kind === "refresh" || this.hostKey === void 0 || next.key === this.hostKey) yield next.notice;
continue;
}
if (this.ended) return;
await new Promise((resolve) => {
this.wake = resolve;
});
this.wake = void 0;
}
} finally {
this.dispose();
}
}
};
/** The stream and followers of one Session and requested path. */
var SessionFeed = class {
onClose;
followers = /* @__PURE__ */ new Set();
stream;
closed = false;
started = false;
acknowledged = false;
/**
* @param remote - the Remote face carrying `workspaceFiles.changes`.
* @param sessionId - the Session whose filesystem this feed observes.
* @param path - target path submitted to the Host.
* @param after - the previous feed of this target still closing, if any; the stream opens once it has settled.
* @param onClose - called once when the stream is gone, whatever the cause, with the dispose that is closing it.
*/
constructor(remote, sessionId, path, after, onClose) {
this.onClose = onClose;
this.stream = remote.$stream({
name: `workspace file changes of ${sessionId}`,
open: (signal) => {
this.started = false;
return openAfter(after, () => remote.workspaceFiles.changes(sessionId, path, signal));
},
ended: () => /* @__PURE__ */ new Error(`workspace file changes of ${sessionId} ended`)
});
this.pump();
}
/**
* Register one resource address before its Host path is known.
* @param follower - receives changes and binds its path after stat.
*/
add(follower) {
this.followers.add(follower);
if (this.started) follower.start();
}
/**
* Unregister one follower; the last one leaving disposes the stream.
* @param follower - the follower to drop.
*/
remove(follower) {
this.followers.delete(follower);
if (this.followers.size === 0) this.close();
}
async pump() {
try {
for await (const item of this.stream) {
const frame = item.value;
switch (frame.kind) {
case "ready":
item.accept();
this.started = true;
for (const follower of this.followers) {
follower.start();
if (this.acknowledged) follower.push({ kind: "refresh" }, "");
}
this.acknowledged = true;
break;
case "change": {
const key = keyOf(frame.change.absolutePath);
const notice = editOf(frame.change);
for (const follower of this.followers) follower.push(notice, key);
break;
}
default: assertNever(frame);
}
}
} catch {} finally {
this.close();
}
}
close() {
if (this.closed) return;
this.closed = true;
const closed = this.stream.dispose();
for (const follower of this.followers) follower.end();
this.followers.clear();
this.onClose(closed);
}
};
/**
* Open a Host stream once a predecessor has finished closing.
* @param after - the predecessor's dispose, or nothing to wait for.
* @param open - opens the stream.
* @returns the stream's items.
*/
async function* openAfter(after, open) {
await after;
yield* open();
}
/**
* The write one Host frame reports.
* @param frame - the Host frame.
* @returns the edit notice followers receive.
*/
function editOf(frame) {
return "absent" in frame ? { kind: "absent" } : {
kind: "changed",
version: frame.version
};
}
function assertNever(frame) {
throw new Error(`Unexpected workspace file watch frame: ${JSON.stringify(frame)}`);
}
/**
* Per-target sharing of the Host's workspace file change streams.
*
* Owned by the provider; one instance serves every session of the Client.
*/
var ChangeFeed = class {
remote;
/** Live feeds only: a feed removes itself when its stream closes. */
sessions = /* @__PURE__ */ new Map();
/** Streams still closing, by Session and path; a successor waits for its predecessor. */
closing = /* @__PURE__ */ new Map();
/**
* @param remote - the Remote face carrying `$stream` and `workspaceFiles.changes`.
*/
constructor(remote) {
this.remote = remote;
}
/**
* Follow one resource in one session before its Host path is known.
*
* The follower is registered on call, not on first pull. Changes delivered
* to this Client are queued while stat is pending. The first follower starts
* target's local `changes` call. The iterable ends
* when `signal` aborts or when the target stream is gone; ending it early
* (`break`, `return`) unregisters the follower as well, and the last follower
* of a target disposes its stream. Await a true `ready` result before stat
* so the Host subscription is active, then bind each stat's absolute path. Until binding,
* any target invalidation can trigger a retry; after binding, only matching queued
* and live changes pass.
* @param sessionId - the Session providing the file's read authority.
* @param path - requested file path; followers share a stream only for the same Session and path.
* @param signal - ends the follow.
* @returns a single-consumer subscription with Host-path binding and explicit disposal.
*/
follow(sessionId, path, signal) {
const feed = signal.aborted ? void 0 : this.feedOf(sessionId, path);
const leave = () => {
signal.removeEventListener("abort", leave);
follower.end();
feed?.remove(follower);
};
const follower = new Follower(leave);
if (feed === void 0) follower.end();
else {
feed.add(follower);
signal.addEventListener("abort", leave, { once: true });
}
return follower;
}
/**
* Wait for every stream that is still closing, so an owner tearing down
* leaves no Host stream behind.
* @returns resolves once no stream of this feed is closing.
*/
async settle() {
await Promise.all(this.closing.values());
}
feedOf(sessionId, path) {
const key = JSON.stringify([sessionId, path]);
const existing = this.sessions.get(key);
if (existing !== void 0) return existing;
const feed = new SessionFeed(this.remote, sessionId, path, this.closing.get(key), (closed) => {
this.sessions.delete(key);
const tracked = closed.then(() => void 0, () => void 0).then(() => {
if (this.closing.get(key) === tracked) this.closing.delete(key);
});
this.closing.set(key, tracked);
});
this.sessions.set(key, feed);
return feed;
}
};
//#endregion
//#region ../../typert/protocol/lib/index.js
/** The one Remote failure class shared by owners, the Gateway, and consumers. */
/**
* One Remote call failure: a real Error carrying its stable code and typed
* details. Owners throw it at the failure point; the Host Gateway encodes it
* onto the wire unchanged; the Client face rebuilds an instance for the
* `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
* Discrimination is always by `code`, never by instanceof.
*/
var RemoteError = class extends Error {
code;
details;
/** Structural marker: cross-realm/bundle identification never uses instanceof. */
isDSHRemoteError = true;
/**
* @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
* @param message - human diagnostic carried across the wire.
* @param details - structured payload typed by the code.
* @param options - standard Error options (`cause` survives in-process only).
*/
constructor(code, message, details, options) {
super(message, options);
this.code = code;
this.details = details;
this.name = "RemoteError";
}
};
//#endregion
//#region ../../util/workspace-path/lib/index.js
/**
* The `dsh-resource://file/…` address grammar: how a file is named across the
* Sidebar and the resource model, built and parsed without touching a
* filesystem.
* @module
*/
/** The scheme and type every file address opens with. */
const FILE_ADDRESS_PREFIX = "dsh-resource://file/";
/** Whether a decoded first path segment is a Windows drive (`C:`). */
function isDriveSegment(segment) {
return segment !== void 0 && /^[A-Za-z]:$/.test(segment);
}
/**
* Read a file address back into its parts without resolving `.` or `..`.
* Query and fragment suffixes are ignored; encoded path segments are decoded.
* @param address - a candidate address.
* @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded.
*/
function parseFileAddress(address) {
try {
if (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0;
const end = address.search(/[?#]/);
const [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split("/");
if (scope === "session") {
const [id, ...segments] = rest;
if (id === void 0 || id === "" || segments.length === 0) return void 0;
return {
scope,
sessionId: decodeURIComponent(id),
path: segments.map(decodeURIComponent).join("/")
};
}
if (scope === "absolute") {
const unc = rest[0] === "" && rest.length > 1;
const segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent);
if (segments.length === 0 || segments[0] === "") return void 0;
if (unc) return {
scope,
path: `//${segments.join("/")}`
};
return {
scope,
path: isDriveSegment(segments[0]) ? segments.join("/") : `/${segments.join("/")}`
};
}
return;
} catch {
return;
}
}
//#endregion
//#region lib/types/client/provider.js
/**
* Build the `file` provider over one Remote face and one change feed.
* @param remote - the Remote face carrying `workspaceFiles.stat`.
* @param changes - target-scoped change streams shared by file resources.
* @returns the provider to register into `ctx.resources`.
*/
function createFileResourceProvider(remote, changes) {
return {
protocol: "file",
async *open(address, { signal }) {
const resolved = resolve(address);
if (!resolved.ok) {
yield resolved;
return;
}
const { sessionId, path } = resolved.value;
const notices = changes.follow(sessionId, path, signal);
const stat = () => remote.workspaceFiles.stat(sessionId, path, signal);
const aborted = () => signal.aborted;
let current;
try {
if (!await notices.ready) {
if (aborted()) return;
const result = await stat();
if (!aborted()) yield result;
return;
}
if (aborted()) return;
const first = await stat();
if (aborted()) return;
if (first.ok) {
notices.bind(first.value.absolutePath);
current = first.value;
yield {
ok: true,
value: current
};
} else yield first;
for await (const notice of notices) {
if (aborted()) return;
if (current === void 0) {
if (notice.kind === "absent") continue;
} else if (notice.kind === "changed") {
if (notice.version === current.version) continue;
}
const again = await stat();
if (aborted()) return;
if (!again.ok) {
current = void 0;
yield again;
continue;
}
notices.bind(again.value.absolutePath);
current = again.value;
yield {
ok: true,
value: current
};
}
} finally {
notices.dispose();
}
}
};
}
/**
* Resolve one address to the Host call it stands for, or to the failure frame it earns.
* @param address - the full address, scheme included.
* @returns the Host file, or the `unsupported-address` / `unknown-workspace` failure.
*/
function resolve(address) {
const parsed = parseFileAddress(address);
if (parsed === void 0) return {
ok: false,
error: unsupportedAddress(address)
};
if (parsed.scope === "session") return {
ok: true,
value: {
sessionId: parsed.sessionId,
path: parsed.path
}
};
return {
ok: false,
error: unknownWorkspace(address)
};
}
/**
* The failure frame's error for an address this provider does not serve.
* @param address - the offending address.
* @returns the typed error.
*/
function unsupportedAddress(address) {
return new RemoteError("workspace-file/unsupported-address", `${address} is not a dsh-resource://file/session/<sessionId>/<path> or dsh-resource://file/absolute/<path> address`, { address });
}
/**
* The failure frame's error for an absolute address with no Session.
* @param address - the offending address.
* @returns the typed error.
*/
function unknownWorkspace(address) {
return new RemoteError("workspace-file/unknown-workspace", `${address} requires a dsh-resource://file/session/<sessionId>/<path> address`, { address });
}
//#endregion
//#region lib/types/client/index.js
/** Required browser services: the resource model, the Remote carrier and its namespace. */
const inject = [
"resources",
"remote",
"remote.workspaceFiles"
];
/**
* Client plugin body: register the `file` provider for this plugin's lifetime.
* @param ctx - client root context carrying `resources` and the Remote face.
*/
function apply(ctx) {
const changes = new ChangeFeed(ctx.remote);
const provider = createFileResourceProvider(ctx.remote, changes);
ctx.effect(() => {
const release = ctx.resources.register(provider);
return async () => {
release();
await changes.settle();
};
}, "workspace-files: file resource provider");
}
//#endregion
exports.apply = apply;
exports.inject = inject;
return module.exports;
}
});
;
//# sourceMappingURL=??@deepseek-ai/dsh-api-workspace-files/client.js.map&rev=6c462da1fc74

0
pytest.ini 100644 → 100755
View File

0
requirements-dev.txt 100644 → 100755
View File

0
requirements.txt 100644 → 100755
View File

0
scripts/README.md 100644 → 100755
View File

0
scripts/import_custom_ledger.py 100644 → 100755
View File

0
scripts/import_excel.py 100644 → 100755
View File

0
scripts/import_staff.py 100644 → 100755
View File

0
scripts/init_db.py 100644 → 100755
View File

0
scripts/legacy/README.md 100644 → 100755
View File

0
scripts/legacy/add_entry_date.py 100644 → 100755
View File

View File

0
scripts/legacy/merge_project.py 100644 → 100755
View File

0
scripts/legacy/migrate_custom.py 100644 → 100755
View File

0
scripts/legacy/shift_year.py 100644 → 100755
View File

View File

@ -262,6 +262,52 @@ if [ "$NEED_INSTALL" = "1" ]; then
fi
log " 依赖检查:OK"
# ---------- 4.5 前端:装依赖 + 构建(nex.config.yaml 标准栈:npm + Vite)----------
# 后端只托管 web/dist 的构建产物;没构建时 app/main.py 退回 web/legacy(改造前的零构建版),
# 所以缺 node 的机器也能先把服务跑起来,只是界面是旧版。
# WEB=0 跳过前端构建(用现有 dist / legacy)
# WEB=1 需要时才构建(默认) WEB=force 每次都重建
WEB="${WEB:-$(env_get WEB)}"
WEB="${WEB:-1}"
NPM_REGISTRY="${NPM_REGISTRY:-$(env_get NPM_REGISTRY)}"
NPM_REGISTRY="${NPM_REGISTRY:-https://registry.npmmirror.com}"
need_build() {
[ "${WEB}" = "0" ] && ${ log " 前端构建:跳过(WEB=0)"; return 1; }
[ -f web/dist/index.html ] || return 0
[ "${WEB}" = "force" ] && return 0
# dist 比任何源文件旧就重建(配置 / src / lockfile)
[ -z "$(find web/src web/index.html web/vite.config.ts web/tsconfig.json web/package-lock.json -newer web/dist/index.html 2>/dev/null | head -1)" ] && ${ log " 前端构建:已是最新,跳过"; return 1; }
return 0
}
if ! command -v npm >/dev/null 2>&1; then
if [ -f web/dist/index.html ]; then
warn "未找到 npm(需 Node 20+):直接用现有前端构建产物 web/dist"
else
warn "未找到 npm 且没有 web/dist:界面退回零构建旧版(web/legacy)。装好 Node 再跑本脚本即切回新版。"
fi
elif need_build; then
if [ ! -d web/node_modules ]; then
log "==> 安装前端依赖(首次约 1~2 分钟,源:${NPM_REGISTRY})"
# 网络盘 / SMB 挂载上 chmod 会被拒(EPERM),这时退一步用 --no-bin-links 装(下面构建时有对应兜底)
( cd web && npm ci --no-audit --no-fund --registry "${NPM_REGISTRY}" 2>/dev/null \
|| npm ci --no-audit --no-fund --no-bin-links --registry "${NPM_REGISTRY}" 2>/dev/null \
|| npm install --no-audit --no-fund --registry "${NPM_REGISTRY}" \
|| npm install --no-audit --no-fund --no-bin-links --registry "${NPM_REGISTRY}" ) \
|| die "前端依赖安装失败。手动执行:cd web && npm ci --registry ${NPM_REGISTRY}"
fi
log "==> 构建前端(Vite)"
if [ -x web/node_modules/.bin/vite ] || [ -f web/node_modules/.bin/vite ]; then
( cd web && npm run build ) || die "前端构建失败:cd web && npm run build 看报错"
else
# --no-bin-links 装的包没有 node_modules/.bin,直接调入口脚本,效果与 npm run build 相同
( cd web && node node_modules/typescript/bin/tsc --noEmit && node node_modules/vite/bin/vite.js build ) \
|| die "前端构建失败:cd web && node node_modules/vite/bin/vite.js build 看报错"
fi
log " 前端构建:OK(web/dist)"
fi
# ---------- 5. 首次运行:建表 + 预置分类 ----------
if [ ! -f data/board.db ]; then
log "==> 首次运行,初始化数据库"

0
tests/conftest.py 100644 → 100755
View File

0
tests/test_ai_export.py 100644 → 100755
View File

117
tests/test_api_contract.py 100644 → 100755
View File

@ -235,37 +235,114 @@ def test_AI落库校验状态与进度(h):
assert r.status_code == 400 and "数字" in r.json()["detail"], r.text
def test_前端查询参数必须在后端有声明(h):
"""批次 D 抓到过「前端一直发 keyword=、后端一直丢」的整类 bug——立两道静态防线:
1) 完整 URL 模板串(含引号串)上的静态键 → 必须出现在该路由的 OpenAPI parameters 里(严格);
2) q.push("key=") 拼接式的键 → 必须至少是某个后端端点声明过的参数(防凭空键名)。"""
"""批次 D 抓到过「前端一直发 keyword=、后端一直丢」的整类 bug——立静态防线。
前端换成 React + Vite(web/src)后,查询键集中在接口层 web/src/api/endpoints.ts:
接口层点名发出的每个键必须在后端 OpenAPI 里声明过;视图传上来但接口层没点名的键会被丢掉
(等于不发),所以守住接口层这一张表就够,口径见 web/src/api/endpoints.ts 顶部注释。"""
import pathlib
import re
js = pathlib.Path("web/app.js").read_text(encoding="utf-8")
src = pathlib.Path("web/src/api/endpoints.ts").read_text(encoding="utf-8")
views = pathlib.Path("web/src")
spec = h.admin.get("/api/openapi.json").json()
routes: dict[str, set] = {}
for path, ops in spec["paths"].items():
for op in ops.values():
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + path)
routes.setdefault(rt, set()).update(p["name"] for p in op.get("parameters", []))
any_param = {k for ks in routes.values() for k in ks}
problems, strict = [], 0
# 形态一:"/route?k=&k2=" 或 `/route?k=${...}&k2=${...}` —— 键直接挂在具体路由上
for m in re.finditer(r'["\x60](/[a-z0-9_/-]+)\?([a-z_]+=[^"\x60]*)["\x60$]', js):
route = "/api" + m.group(1)
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", route)
body_routes: dict[str, set] = {}
body_keys: dict[str, set] = {}
problems = []
strict = 0
def check(route, keys_blob, where):
nonlocal strict
if "{" in route:
return # 路径参数拼在路由里,不是查询串,不误报
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route)
if rt not in routes:
continue # 路由拼在变量里匹配不上,不误报
return # 路由拼在变量里匹配不上,不误报
strict += 1
for key in [k for k in re.findall(r"([a-z_]+)=", m.group(0)) if k != "api"]:
for key in re.findall(r"([a-z_]+)\s*:", keys_blob):
if key not in routes[rt]:
problems.append(f"严格:{rt} 收到 {key}= 后端未声明")
# 形态二:q.push("key=" ...) 拼接
loose = 0
for m in re.finditer(r'push\("(&?)([a-z_]+)=', js):
loose += 1
if m.group(2) not in any_param:
problems.append(f"宽松:拼了 {m.group(2)}= 但全后端没有任何端点声明它")
assert strict + loose >= 12, f"只扫到 严格{strict}+宽松{loose} 处,正则可能失效"
problems.append(where + ":" + rt + " 发 " + key + "= 后端未声明")
# 形态一:接口层函数调用 + 对象字面量。get/del 的字面量是查询参数(对 OpenAPI parameters);
# post/patch/put 的字面量是 JSON body(对 requestBody schema 的属性,schema 没属性就跳过)
for m in re.finditer(r'(get|post|patch|del|put)(?:<[^>]*>)?\(\s*"(/[a-z0-9_/{}.-]+)"\s*,\s*\{([^)]*?)\}', src, re.S):
verb, route, blob = m.group(1), m.group(2), m.group(3)
if verb in ("get", "del"):
check(route, blob, "接口层查询")
else:
for sub in re.finditer(r'\{\s*([a-z_]+)\s*:', " " + blob):
pass # 嵌套对象(如 settings 的 values)由内层再扫一次
body_routes.setdefault(re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route), set()).add(verb)
body_keys.setdefault(re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + route), set()).update(re.findall(r"([a-z_]+)\s*:", blob))
# 形态二:导出 URL —— "/export/xxx" + tail({ key: ... })
for m in re.finditer(r'"(/[a-z0-9_/-]+)"\s*\+\s*tail\(\{([^)]*?)\}', src, re.S):
check(m.group(1), m.group(2), "导出")
# 形态三:视图里手写的 ?k= 完整串(正常应该没有,出现就必须对得上)
for f in sorted(views.rglob("*.ts*")):
if f.name == "endpoints.ts":
continue
for m in re.finditer(r'["`@](/[a-z0-9_/-]+)\?([a-z_]+=[^"`]*)["]$]', f.read_text(encoding="utf-8")):
check(m.group(1), m.group(2), f.name)
# 写请求的 body 键:与 requestBody schema 的属性名对表(schema 未声明属性的接口跳过)
body_props: dict[str, set] = {}
for path, ops in spec["paths"].items():
for verb, op in ops.items():
if not isinstance(op, dict):
continue
rt = re.sub(r"\{[a-zA-Z_]+\}", "0", "/api" + path) + "#" + verb
sch = ((op.get("requestBody") or {}).get("content") or {}).get("application/json", {}).get("schema") or {}
name = (sch.get("$ref") or "").split("/")[-1]
props = ((spec.get("components", {}).get("schemas", {}).get(name) or {}).get("properties") or {}) if name else {}
if props:
body_props.setdefault(rt, set()).update(props.keys())
for rt, keys in body_keys.items():
for verb in body_routes.get(rt, set()):
props = body_props.get(rt + "#" + verb)
if not props:
continue
strict += 1
for k in sorted(keys - props):
if k not in {"values", "parsed", "targets"}: # 再嵌套一层的容器键由内层键把关
problems.append("接口层body:" + rt + " 的 " + k + " 后端 body 未声明")
assert strict >= 12, "只扫到 " + str(strict) + " 处带查询键的调用,正则可能失效"
assert not problems, "\n".join(problems)
def test_正文富文本按约定存_按纯文本出表(h):
"""正文支持简单富文本:前端编辑器只发 <b>/<i>/<u>/<br>/<span data-c="语义色"> 这一小组标签
(约定见 web/src/utils/richtext.ts),库里原样存,Excel 出表必须降级成纯文本。
这条约定是编辑器、展示端、导出三处共用的,改任何一边都要同步,所以钉在契约测试里。"""
from io import BytesIO
from openpyxl import load_workbook
from app.export import plain
rich = '<b>完成联调</b>与<span data-c="danger">3 项阻塞</span><br>下周<i>验收</i>&amp;交付'
assert plain(rich) == "完成联调与3 项阻塞\n下周验收&交付"
# 编辑器(Tiptap)产出每行一个 <p>:相邻段落只算一个换行,空段落算一个空行,别凭空多打行
assert plain("<p>L1</p><p>L2</p><p><br></p><p><b>L4</b></p>") == "L1\nL2\n\nL4"
assert plain("<p>就一行</p>") == "就一行"
assert plain("A<b 项目") == "A<b 项目" # 名称里的尖括号不能被误伤
assert plain(None) is None and plain(12.5) == 12.5 # 非字符串原样走
r = h.admin.post("/api/focus", json={"content": "富文本导出验证", "detail": rich})
assert r.status_code == 200, r.text
fid = r.json()["id"]
try:
x = h.admin.get("/api/export/focus", params={"archived": "all"})
assert x.status_code == 200
ws = load_workbook(BytesIO(x.content)).active
cells = [c.value for row in ws.iter_rows() for c in row if isinstance(c.value, str)]
assert any("富文本导出验证" in v for v in cells), "新建的重点工作没进导出"
detail = [v for v in cells if "下周" in v]
assert detail, "说明列没导出到"
assert "<" not in detail[0] and "data-c" not in detail[0], detail[0]
assert "完成联调与3 项阻塞" in detail[0]
finally:
assert h.admin.delete("/api/focus/" + str(fid)).status_code == 200

0
tests/test_auth.py 100644 → 100755
View File

0
tests/test_custom_finance.py 100644 → 100755
View File

0
tests/test_periods_projects.py 100644 → 100755
View File

0
tests/test_rbac.py 100644 → 100755
View File

0
tests/test_staff_focus_weekly.py 100644 → 100755
View File

126
web/index.html 100644 → 100755
View File

@ -1,117 +1,13 @@
<!DOCTYPE html>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DMS管理平台</title>
<link rel="stylesheet" href="/static/styles.css" />
</head>
<body>
<div class="app">
<aside class="sidebar">
<div class="brand">
<div class="brand-mark"><i data-icon="target"></i></div>
<div class="brand-text">
<strong>DMS管理平台</strong>
<span>软件开发部</span>
</div>
<!-- 收拢后这颗按钮换成展开图标,平时隐藏,hover 到 logo 上出现;按钮自身不挂 tips -->
<button class="nav-fold" id="navFold" aria-label="收起菜单">
<i class="ic-fold" data-icon="panel-collapse"></i><i class="ic-unfold" data-icon="panel-expand"></i>
</button>
</div>
<nav class="nav" id="nav">
<button class="nav-item active" data-view="board"><span class="ni" data-icon="board"></span><span class="nl">工作看板</span></button>
<button class="nav-item" data-view="projects"><span class="ni" data-icon="list-checks"></span><span class="nl">自研产品</span></button>
<button class="nav-item" data-view="custom"><span class="ni" data-icon="package"></span><span class="nl">定制项目</span></button>
<button class="nav-item" data-view="focus"><span class="ni" data-icon="target"></span><span class="nl">每周工作</span></button>
<div class="nav-label">支撑</div>
<button class="nav-item" data-view="staff"><span class="ni" data-icon="users"></span><span class="nl">人力资源</span></button>
<button class="nav-item" data-view="intake"><span class="ni" data-icon="pencil"></span><span class="nl">更新录入</span></button>
<button class="nav-item" data-view="settings"><span class="ni" data-icon="sliders"></span><span class="nl">设置</span></button>
<button class="nav-item" data-view="rbac"><span class="ni" data-icon="shield-check"></span><span class="nl">权限管理</span></button>
</nav>
<div class="side-user" id="sideUser"></div>
</aside>
<main class="main">
<header class="topbar">
<div class="period-bar">
<div class="seg" id="granSeg">
<button class="seg-btn active" data-gran="week">周</button>
<button class="seg-btn" data-gran="month">月</button>
</div>
<button class="nav-arrow" id="prevPeriod" title="上一期"><i data-icon="chevron-left"></i></button>
<select id="periodSelect" class="period-select"></select>
<button class="nav-arrow" id="nextPeriod" title="下一期"><i data-icon="chevron-right"></i></button>
<span class="period-hint" id="periodHint"></span>
</div>
<div class="topbar-right">
<input id="globalSearch" class="search" type="search" placeholder="搜索项目 / 内容…" />
<button class="btn primary" id="btnIntake"><i data-icon="plus"></i>更新录入</button>
</div>
</header>
<div class="views">
<section class="view" id="view-board"></section>
<section class="view hidden" id="view-projects"></section>
<section class="view hidden" id="view-custom"></section>
<section class="view hidden" id="view-focus"></section>
<section class="view hidden" id="view-staff"></section>
<section class="view hidden" id="view-intake"></section>
<section class="view hidden" id="view-settings"></section>
<section class="view hidden" id="view-rbac"></section>
</div>
</main>
</div>
<div class="drawer-mask" id="drawerMask"></div>
<aside class="drawer" id="drawer">
<div class="drawer-head">
<div class="drawer-head-text">
<h3 id="drawerTitle">项目详情</h3>
<div class="drawer-sub" id="drawerSub"></div>
</div>
<div class="btn-bar" id="drawerActions"></div>
<button class="icon-btn" id="drawerClose" title="关闭"><i data-icon="x"></i></button>
</div>
<div class="drawer-body" id="drawerBody"></div>
</aside>
<div class="modal-mask" id="modalMask">
<div class="modal" id="modal"></div>
</div>
<div class="auth-mask hidden" id="authGate">
<div class="auth-shell">
<!-- 左:品牌区 -->
<aside class="auth-brand">
<div class="ab-top">
<div class="brand-mark"><i data-icon="target"></i></div>
<div class="brand-text"><strong>DMS管理平台</strong><span>软件开发部</span></div>
</div>
<div class="ab-mid"><h2>进展、风险、计收<br>一张看板看完</h2></div>
</aside>
<!-- 右:登录表单 -->
<form class="auth-form" id="authForm" autocomplete="on">
<h3>登录</h3>
<p class="af-sub">使用部门分配的账号</p>
<label class="af-field"><span>账号</span>
<input class="inp" id="authUser" autocomplete="username" placeholder="请输入账号" /></label>
<label class="af-field"><span>密码</span>
<input class="inp" id="authPass" type="password" autocomplete="current-password" placeholder="请输入密码" /></label>
<div class="notice err" id="authErr" style="display:none"></div>
<button class="btn primary block" type="submit" id="authOk">登录<i data-icon="arrow-right"></i></button>
</form>
</div>
</div>
<div class="toast" id="toast"></div>
<script src="/static/icons.js"></script>
<script src="/static/app.js"></script>
<script src="/static/livereload.js"></script>
</body>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="light" />
<title>DMS管理平台</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

1017
web/app.js → web/legacy/app.js 100644 → 100755

File diff suppressed because it is too large Load Diff

View File

@ -17,6 +17,7 @@
users: '<circle cx="9.4" cy="8" r="3.4"/><path d="M3 20a6.4 6.4 0 0112.8 0"/><path d="M16.4 5.4a3.4 3.4 0 010 5.2"/><path d="M18.4 14.7A6.4 6.4 0 0121 20"/>',
pencil: '<path d="M4 20.2l.9-4L16.2 4.9a2.1 2.1 0 013 3L7.9 19.3l-3.9.9z"/><path d="M14.8 6.3l2.9 2.9"/>',
sliders: '<path d="M5 7h8.8M18.6 7H21M5 17h3.4M12.8 17h5.2"/><circle cx="16" cy="7" r="2.2"/><circle cx="10.6" cy="17" r="2.2"/>',
menu: '<path d="M4 7.2h16M4 12h16M4 16.8h16"/>',
"panel-collapse": '<rect x="3.4" y="4.2" width="17.2" height="15.6" rx="2.4"/><path d="M9.8 4.2v15.6"/><path d="M16.6 9.4L13.4 12l3.2 2.6"/>',
"panel-expand": '<rect x="3.4" y="4.2" width="17.2" height="15.6" rx="2.4"/><path d="M9.8 4.2v15.6"/><path d="M13.4 9.4l3.2 2.6-3.2 2.6"/>',
/* 通用动作 */
@ -160,7 +161,7 @@
if (!root) return;
if (root.nodeType === 1) fill(root);
if (!root.querySelectorAll) return;
var nodes = root.querySelectorAll("[data-icon], .card-head h4, .sec-title, .wk-group-head, .empty, .notice");
var nodes = root.querySelectorAll("[data-icon], .card-head h3, .sec-title, .wk-group-head, .empty, .notice");
fillAll(nodes);
}
@ -174,7 +175,7 @@
el.removeAttribute("data-icon");
return;
}
if (el.matches(".card-head h4, .sec-title, .wk-group-head")) {
if (el.matches(".card-head h3, .sec-title, .wk-group-head")) {
// 模板里已经自带前导图标的标题不再自动补第二个
if (el.querySelector(":scope > .ic")) { el.setAttribute("data-ico", "1"); return; }
leadingIcon(el, pickIcon(text(el), TITLE_ICON), "ti");

View File

@ -0,0 +1,128 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DMS管理平台</title>
<link rel="stylesheet" href="/static/styles.css" />
</head>
<body>
<!-- 键盘用户第一个落点:跳过导航直达内容区 -->
<a class="skip-link" href="#mainContent">跳到主要内容</a>
<div class="app" id="app">
<aside class="sidebar" id="sidebar">
<div class="brand">
<div class="brand-mark"><i data-icon="target"></i></div>
<div class="brand-text">
<h1>DMS管理平台</h1>
<span>软件开发部</span>
</div>
<!-- 收拢后这颗按钮换成展开图标,平时隐藏,hover 到 logo 上出现;按钮自身不挂 tips -->
<button class="nav-fold" id="navFold" aria-label="收起菜单" aria-expanded="true" aria-controls="nav">
<i class="ic-fold" data-icon="panel-collapse"></i><i class="ic-unfold" data-icon="panel-expand"></i>
</button>
</div>
<nav class="nav" id="nav" aria-label="功能菜单">
<button class="nav-item active" data-view="board" aria-current="page"><span class="ni" data-icon="board"></span><span class="nl">工作看板</span></button>
<button class="nav-item" data-view="projects"><span class="ni" data-icon="list-checks"></span><span class="nl">自研产品</span></button>
<button class="nav-item" data-view="custom"><span class="ni" data-icon="package"></span><span class="nl">定制项目</span></button>
<button class="nav-item" data-view="focus"><span class="ni" data-icon="target"></span><span class="nl">每周工作</span></button>
<div class="nav-group" role="group" aria-labelledby="navGroupSupport">
<div class="nav-label" id="navGroupSupport">支撑</div>
<button class="nav-item" data-view="staff"><span class="ni" data-icon="users"></span><span class="nl">人力资源</span></button>
<button class="nav-item" data-view="intake"><span class="ni" data-icon="pencil"></span><span class="nl">更新录入</span></button>
<button class="nav-item" data-view="settings"><span class="ni" data-icon="sliders"></span><span class="nl">设置</span></button>
<button class="nav-item" data-view="rbac"><span class="ni" data-icon="shield-check"></span><span class="nl">权限管理</span></button>
</div>
</nav>
<div class="side-user" id="sideUser"></div>
</aside>
<!-- 小屏抽屉导航的遮罩,只在 <=1100 出现 -->
<div class="nav-mask" id="navMask"></div>
<main class="main" id="mainContent" tabindex="-1">
<header class="topbar">
<button class="nav-toggle" id="navToggle" aria-label="打开功能菜单" aria-expanded="false" aria-controls="sidebar"><i data-icon="menu"></i></button>
<div class="period-bar">
<div class="seg" id="granSeg" role="group" aria-label="统计粒度">
<button class="seg-btn active" data-gran="week" aria-pressed="true">周</button>
<button class="seg-btn" data-gran="month" aria-pressed="false">月</button>
</div>
<button class="nav-arrow" id="prevPeriod" title="上一期" aria-label="上一期"><i data-icon="chevron-left"></i></button>
<label class="sr-only" for="periodSelect">选择周期</label>
<select id="periodSelect" class="period-select"></select>
<button class="nav-arrow" id="nextPeriod" title="下一期" aria-label="下一期"><i data-icon="chevron-right"></i></button>
<span class="period-hint" id="periodHint"></span>
</div>
<div class="topbar-right">
<label class="sr-only" for="globalSearch">搜索项目或内容</label>
<input id="globalSearch" class="search" type="search" placeholder="搜索项目 / 内容…" />
<button class="btn primary" id="btnIntake"><i data-icon="plus"></i>更新录入</button>
</div>
</header>
<div class="views">
<section class="view" id="view-board"></section>
<section class="view hidden" id="view-projects"></section>
<section class="view hidden" id="view-custom"></section>
<section class="view hidden" id="view-focus"></section>
<section class="view hidden" id="view-staff"></section>
<section class="view hidden" id="view-intake"></section>
<section class="view hidden" id="view-settings"></section>
<section class="view hidden" id="view-rbac"></section>
</div>
</main>
</div>
<div class="drawer-mask" id="drawerMask"></div>
<aside class="drawer" id="drawer" role="dialog" aria-modal="true" aria-labelledby="drawerTitle">
<div class="drawer-head">
<div class="drawer-head-text">
<h2 class="dlg-title" id="drawerTitle">项目详情</h2>
<div class="drawer-sub" id="drawerSub"></div>
</div>
<div class="btn-bar" id="drawerActions"></div>
<button class="icon-btn" id="drawerClose" title="关闭" aria-label="关闭详情"><i data-icon="x"></i></button>
</div>
<div class="drawer-body" id="drawerBody"></div>
</aside>
<div class="modal-mask" id="modalMask">
<div class="modal" id="modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle" tabindex="-1"></div>
</div>
<div class="auth-mask hidden" id="authGate" role="dialog" aria-modal="true" aria-labelledby="authTitle">
<div class="auth-shell">
<!-- 左:品牌区 -->
<aside class="auth-brand">
<div class="ab-top">
<div class="brand-mark"><i data-icon="target"></i></div>
<div class="brand-text"><h1>DMS管理平台</h1><span>软件开发部</span></div>
</div>
<div class="ab-mid"><h2>进展、风险、计收<br>一张看板看完</h2></div>
</aside>
<!-- 右:登录表单 -->
<form class="auth-form" id="authForm" autocomplete="on">
<h2 id="authTitle">登录</h2>
<p class="af-sub">使用部门分配的账号</p>
<label class="af-field"><span>账号</span>
<input class="inp" id="authUser" autocomplete="username" placeholder="请输入账号" /></label>
<label class="af-field"><span>密码</span>
<input class="inp" id="authPass" type="password" autocomplete="current-password" placeholder="请输入密码" aria-describedby="authErr" /></label>
<div class="notice err" id="authErr" role="alert" style="display:none"></div>
<button class="btn primary block" type="submit" id="authOk">登录<i data-icon="arrow-right"></i></button>
</form>
</div>
</div>
<!-- 唯一的操作结果播报口:Toast 文案在这里被辅助技术读出 -->
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script src="/static/icons.js"></script>
<script src="/static/app.js"></script>
<script src="/static/livereload.js"></script>
</body>
</html>

View File

View File

@ -0,0 +1,982 @@
/* =============================================================
设计语言
· 不允许「彩色描边」:卡片/列表/步骤条一律中性灰边框或无边框
· 重点色只出现在三处:图标、关键数字/文本、小面积 tinted 底板
· 图标统一用 web/icons.js 的线性 SVG(stroke=currentColor,aria-hidden)
· 状态/标签一律走「一个 --c + 派生底色与文字色」,不再各写一套底色
============================================================= */
/* ---------- 断点登记表(唯一来源,改断点只改这里 + 同步引用)----------
<=1180 两栏工作区 / KPI 卡收单列 (grid-collapse)
<=1100 顶栏与宽表开始横向收纳 (nav-collapse:侧栏转抽屉)
<=900 卡头工具栏、周期条转第二行 (toolbar-wrap)
<=780 登录页去掉品牌分栏 (auth-compact)
<=640 单列表单、抽屉/弹窗满屏、触控放大 (single-column)
---------------------------------------------------------------------- */
:root {
color-scheme: light;
/* — 文字 — */
--text: #1f2430; /* 主文本 */
--text-2: #4a5261; /* 次级文本 */
--muted: #667085; /* 辅助文本(对 --panel / --bg / --surface-sunken 均 ≥4.5:1)*/
--text-inverse: #fff; /* 深底上的文字(主按钮、气泡、Toast)*/
/* — 表面 — */
--bg: #f4f6f9; /* 画布 */
--panel: #ffffff; /* 卡片 / 面板 */
--panel-2: #fafbfc; /* 面板内的浅底(表头、代码框、只读块)*/
--surface-hover: #f7f9fb; /* 行、菜单项悬停 */
--surface-sunken: #f1f3f7; /* 中性小底板:计数 chip、进度槽、分段控件 */
--surface-inverse: #1f2430; /* 气泡 / Toast 深底 */
--surface-translucent: rgba(255, 255, 255, .9); /* 吸顶工具条 */
--overlay-mask: rgba(18, 24, 38, .42); /* 抽屉 / 弹窗遮罩(唯一值)*/
/* — 边界与焦点 — */
--border: #e9ecf1;
--border-strong: #d4d9e0; /* 可操作控件描边、滚动条、图形占位 */
--focus: var(--primary); /* 焦点环:与主色同源 */
/* — 品牌 / 主色 — */
--primary: #2563eb;
--primary-hover: #1d4ed8;
--primary-soft: #eef4ff; /* 主色小面积底板 */
--on-primary: #fff;
/* — 语义状态(文字色一律 ≥4.5:1;soft 只作小面积底板)— */
--success: #15803d; --success-soft: #e9f7ef;
--warning: #b45309; --warning-soft: #fdf6e9;
--danger: #dc2626; --danger-soft: #fdf0f0;
--danger-strong: #b42318; --danger-border: #f3c6c6;
--info-text: #1e40af;
--violet: #7c3aed; /* 次强调色,只用于 KPI 区分 */
--star: #f0a500; /* 重点标记(图形 + 文案共同表意,不单独承担信息)*/
/* — 圆角 — */
--radius-sm: 8px; /* 控件、chip */
--radius-md: 10px; /* 卡片内的小容器 */
--radius: 12px; /* 卡片 */
--radius-lg: 18px; /* 登录壳 */
--radius-pill: 999px;
/* — 间距(新增/改动处一律取整档,旧值按页面逐步治理,不做无语义的全局替换)— */
--sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px; --sp-5: 20px; --sp-6: 24px; --sp-8: 32px;
/* — 控件高度 / 触控目标 — */
--ctrl-h-xs: 24px;
--ctrl-h-sm: 28px;
--ctrl-h: 32px;
--ctrl-h-lg: 40px;
--touch: 40px; /* 小屏与粗指针下的最小可点尺寸 */
/* — 阴影(5 级,不再新增第六种)— */
--shadow-sm: 0 1px 2px rgba(16, 24, 40, .06);
--shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 6px 20px rgba(16, 24, 40, .05);
--shadow-pop: 0 4px 14px rgba(16, 24, 40, .18);
--shadow-lg: 0 10px 28px rgba(16, 24, 40, .14);
--shadow-xl: 0 20px 60px rgba(16, 24, 40, .22);
/* — 动效 — */
--dur-1: .14s; /* 微反馈:hover / 选中 */
--dur-2: .22s; /* 遮罩、Toast */
--dur-3: .28s; /* 抽屉位移、进度条 */
--ease: cubic-bezier(.4, 0, .2, 1);
/* — 层级(唯一来源)— */
--z-sticky: 20; /* 顶栏 */
--z-nav: 25; /* 收拢侧栏的气泡 */
--z-popover: 30; /* 二级菜单、Tooltip */
--z-mask: 40;
--z-drawer: 50;
--z-modal: 60; /* 弹窗遮罩、登录壳 */
--z-toast: 90;
/* — 布局尺寸 — */
--h-topbar: 57px; /* 顶栏实测高:12 + 32 + 12 + 1px 分隔 */
--sidebar-w: 232px;
--sidebar-w-fold: 64px;
--views-pad-x: 22px;
--views-pad-y: 20px;
--card-gap: 16px;
}
* { box-sizing: border-box; }
html, body {
margin: 0; padding: 0; height: 100%;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
-webkit-font-smoothing: antialiased;
}
button, input, select, textarea { font-family: inherit; font-size: inherit; color: inherit; }
/* 焦点环只在权威处定义一次;自定义控件(role="button" / tabindex)同样命中 */
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible,
[tabindex]:focus-visible, [role="button"]:focus-visible, [role="tab"]:focus-visible, [role="columnheader"]:focus-visible {
outline: 2px solid var(--focus); outline-offset: 2px;
}
.skip-link {
position: fixed; left: var(--sp-3); top: calc(-1 * var(--ctrl-h-lg) - 20px); z-index: var(--z-toast);
background: var(--panel); color: var(--primary); font-weight: 600; padding: 8px 14px;
border: 1px solid var(--border); border-radius: var(--radius-sm); box-shadow: var(--shadow-lg);
}
.skip-link:focus { top: var(--sp-3); }
/* 只给辅助技术的文本(标题、状态播报、控件名称) */
.sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
clip-path: inset(50%); white-space: nowrap; border: 0;
}
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: var(--radius-pill); border: 3px solid transparent; background-clip: content-box; }
/* Firefox 走标准属性,保持同一可见度 */
* { scrollbar-color: color-mix(in srgb, var(--border-strong) 80%, transparent) transparent; }
::-webkit-scrollbar-thumb:hover { background: color-mix(in srgb, var(--border-strong) 72%, var(--text)); background-clip: content-box; }
.app { display: flex; min-height: 100vh; }
/* ---------------- 图标基元 ---------------- */
.ic { width: 16px; height: 16px; flex: none; vertical-align: -3px; }
.ic-lg { width: 22px; height: 22px; }
/* 标题前的小图标 */
.ti { width: 15px; height: 15px; flex: none; color: var(--muted); vertical-align: -2px; }
/* 重点色底板:--c 由外层注入(状态色 / 阶段色 / 重点色) */
.ic-badge {
display: inline-grid; place-items: center; flex: none;
width: 32px; height: 32px; border-radius: var(--radius-md);
background: var(--panel-2);
background: color-mix(in srgb, var(--c, var(--primary)) 10%, var(--panel));
color: var(--c, var(--primary));
}
.ic-badge > .ic { width: 18px; height: 18px; }
.ic-badge.sm { width: 26px; height: 26px; border-radius: var(--radius-sm); }
.ic-badge.sm > .ic { width: 15px; height: 15px; }
/* ---------------- sidebar ---------------- */
.sidebar {
width: var(--sidebar-w);
flex: 0 0 var(--sidebar-w);
background: var(--panel);
border-right: 1px solid var(--border);
display: flex; flex-direction: column;
position: sticky; top: 0; height: 100vh;
padding: 18px 14px;
transition: width var(--dur-1) var(--ease), flex-basis var(--dur-1) var(--ease);
}
.brand { position: relative; display: flex; gap: 10px; align-items: center; margin-bottom: 22px; padding: 0 4px; }
.brand-mark {
width: 34px; height: 34px; border-radius: var(--radius-md); flex: none;
background: var(--primary); color: var(--text-inverse);
display: grid; place-items: center;
}
.brand-mark .ic { width: 19px; height: 19px; }
.brand-text { display: flex; flex-direction: column; line-height: 1.3; }
.brand-text h1 { margin: 0; font-size: 14px; font-weight: 600; letter-spacing: .1px; }
.brand-text span { font-size: 11px; color: var(--muted); }
.nav { display: flex; flex-direction: column; gap: 2px; }
.nav-item {
display: flex; align-items: center; gap: 10px;
padding: 9px 10px; border: 0; border-radius: var(--radius-sm);
background: transparent; cursor: pointer; text-align: left;
color: var(--text-2); transition: background var(--dur-1) var(--ease), border-color var(--dur-1) var(--ease), color var(--dur-1) var(--ease);
}
.nav-item:hover { background: var(--panel-2); color: var(--text); }
.nav-item.active { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.ni { display: inline-flex; width: 16px; height: 16px; flex: none; color: var(--muted); }
.ni .ic { width: 16px; height: 16px; }
.nav-item.active .ni { color: var(--primary); }
.switch { display: flex; align-items: center; gap: 8px; padding: 0 4px; cursor: pointer; color: var(--text-2); }
/* 用户信息胶囊:钉在侧栏最下方,点开是向上弹出的二级菜单 */
.side-user { position: relative; margin-top: auto; }
.user-chip {
display: flex; align-items: center; gap: 9px; width: 100%;
padding: 7px 8px; border-radius: var(--radius-md); cursor: pointer;
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
}
.user-chip:hover { border-color: var(--border-strong); background: var(--panel); }
.avatar {
width: 28px; height: 28px; border-radius: var(--radius-md); flex: none;
display: grid; place-items: center; font-size: 12px; font-weight: 600;
background: var(--primary); color: var(--text-inverse);
}
.user-chip .u-text { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; flex: 1; }
.user-chip .u-text b { font-size: 12.5px; font-weight: 600; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.user-chip .u-text i { font-style: normal; font-size: 11px; color: var(--muted); }
.user-chip .ic { width: 15px; height: 15px; color: var(--muted); flex: none; }
.user-menu {
position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: var(--z-popover);
background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius-md);
box-shadow: var(--shadow-lg); padding: 5px; display: flex; flex-direction: column; gap: 2px;
}
.user-menu button {
display: flex; align-items: center; gap: 8px; padding: 8px 9px;
border: 0; background: transparent; border-radius: var(--radius-sm); cursor: pointer;
font-size: 12.5px; color: var(--text-2); text-align: left;
}
.user-menu button:hover { background: var(--panel-2); color: var(--text); }
.user-menu button.danger { color: var(--danger); }
.user-menu button.danger:hover { background: var(--danger-soft); }
.user-menu .ic { width: 15px; height: 15px; }
/* ---------------- 侧栏收拢 ----------------
展开态:收拢按钮贴在 logo 右侧;
收拢态:菜单只留图标(hover 出气泡提示),收拢按钮藏进 logo,hover logo 才变成展开按钮。 */
.nav-fold {
margin-left: auto; width: var(--ctrl-h-sm); height: var(--ctrl-h-sm); flex: none; padding: 0;
border: 1px solid var(--border); border-radius: var(--radius-sm);
background: var(--panel-2); color: var(--muted);
display: grid; place-items: center; cursor: pointer; transition: background var(--dur-1) var(--ease), border-color var(--dur-1) var(--ease), color var(--dur-1) var(--ease);
}
.nav-fold:hover { color: var(--primary); border-color: var(--border-strong); background: var(--panel); }
.nav-fold .ic { width: 15px; height: 15px; }
.nav-fold .ic-unfold { display: none; }
/* 气泡提示:只给收拢后的菜单图标(收拢/展开按钮上不出提示) */
.app.nav-folded .nav-item[data-tip]:hover::after,
.app.nav-folded .nav-item[data-tip]:focus-visible::after {
content: attr(data-tip); position: absolute; left: calc(100% + 8px); top: 50%;
transform: translateY(-50%); white-space: nowrap; z-index: var(--z-popover); pointer-events: none;
background: var(--surface-inverse); color: var(--text-inverse); font-size: 12px; font-weight: 400;
padding: 5px 9px; border-radius: var(--radius-sm); box-shadow: var(--shadow-pop);
}
/* 侧栏是 sticky,自成层叠上下文:不提层级的话气泡会被内容区里靠后定位的元素(如每周工作的吸顶卡片)盖住 */
.app.nav-folded .sidebar { z-index: var(--z-nav); }
.app.nav-folded { --sidebar-w: var(--sidebar-w-fold); }
.app.nav-folded .brand { justify-content: center; }
.app.nav-folded .brand-text, .app.nav-folded .nav-item .nl,
.app.nav-folded .user-chip .u-text, .app.nav-folded .user-chip .ic { display: none; }
.app.nav-folded .nav-item { justify-content: center; gap: 0; padding: 9px 0; position: relative; }
.app.nav-folded .nav-label { font-size: 0; height: 1px; background: var(--border); margin: 10px 6px 4px; padding: 0; }
.app.nav-folded .user-chip { justify-content: center; padding: 3px; }
.app.nav-folded .user-menu { left: 0; right: auto; min-width: 168px; }
.app.nav-folded .nav-fold {
position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
width: 34px; height: 34px; border-radius: var(--radius-md); border-color: transparent;
background: var(--primary-soft); color: var(--primary); opacity: 0; pointer-events: none;
}
.app.nav-folded .brand:hover .brand-mark { opacity: 0; }
.app.nav-folded .brand:hover .nav-fold,
.app.nav-folded .brand:focus-within .nav-fold { opacity: 1; pointer-events: auto; }
.app.nav-folded .nav-fold .ic-fold { display: none; }
.app.nav-folded .nav-fold .ic-unfold { display: inline-flex; }
/* ---------------- 登录(左右分栏) ---------------- */
/* 登录页的品牌渐变与光斑是一次性装饰,不进入全局 Token;例外只在这两个选择器内定义。 */
.auth-mask { --auth-glow: #e2ecfd;
position: fixed; inset: 0; z-index: var(--z-modal); display: grid; place-items: center; padding: 28px;
background: var(--bg) radial-gradient(900px 520px at 12% -10%, var(--auth-glow), transparent 70%); }
.auth-shell { width: min(880px, 100%); display: grid; grid-template-columns: 1.05fr .95fr;
background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden;
box-shadow: var(--shadow-xl); }
/* 左:品牌区 */
.auth-brand { --auth-g1: #16255c; --auth-g2: #1f3f9e; --auth-g3: #3b5fd0;
--auth-ink: #e8f0ff; --auth-ink-70: rgba(232, 240, 255, .7); --auth-ink-85: rgba(232, 240, 255, .85);
position: relative; overflow: hidden; padding: 34px 34px 30px;
display: flex; flex-direction: column; gap: 28px; color: var(--auth-ink);
background: linear-gradient(155deg, var(--auth-g1) 0%, var(--auth-g2) 52%, var(--auth-g3) 100%); }
.auth-brand::before, .auth-brand::after { content: ""; position: absolute; border-radius: 50%; pointer-events: none; }
.auth-brand::before { width: 360px; height: 360px; right: -170px; top: -130px;
background: radial-gradient(closest-side, color-mix(in srgb, var(--panel) 17%, transparent), transparent); }
.auth-brand::after { width: 260px; height: 260px; left: -130px; bottom: -140px;
background: radial-gradient(closest-side, color-mix(in srgb, var(--auth-g3) 55%, var(--panel)) , transparent); }
.auth-brand .brand-mark { background: color-mix(in srgb, var(--panel) 16%, transparent); color: var(--text-inverse); }
.ab-top { position: relative; display: flex; align-items: center; gap: 11px; }
.ab-top .brand-text h1 { color: var(--text-inverse); }
.ab-top .brand-text span { color: var(--auth-ink-70); }
.ab-mid { position: relative; margin: auto 0; }
.ab-mid h2 { margin: 0 0 20px; font-size: 23px; line-height: 1.42; font-weight: 600; letter-spacing: .2px; }
.ab-mid ul { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 11px; }
.ab-mid li { display: flex; align-items: center; gap: 10px; font-size: 12.5px; color: var(--auth-ink-85); }
.ab-mid li .ic { width: 15px; height: 15px; flex: none; opacity: .85; }
/* 右:表单 */
.auth-form { padding: 40px 40px 32px; display: flex; flex-direction: column; }
.auth-form h3 { margin: 0; font-size: 21px; letter-spacing: .2px; }
.af-sub { margin: 6px 0 26px; font-size: 12.5px; color: var(--muted); }
.af-field { display: block; margin-bottom: 15px; }
.af-field > span { display: block; margin-bottom: 6px; font-size: 12px; color: var(--text-2); }
.af-field .inp { width: 100%; height: var(--ctrl-h-lg); }
.af-field .inp::placeholder { color: var(--muted); opacity: .8; }
.auth-form .notice.err { margin-bottom: 14px; }
.btn.block { width: 100%; height: var(--ctrl-h-lg); margin-top: 8px; justify-content: center; gap: 7px; }
.btn.block .ic { width: 16px; height: 16px; }
@media (max-width: 780px) {
.auth-mask { padding: 16px; }
.auth-shell { grid-template-columns: 1fr; }
.auth-brand { padding: 18px 20px; gap: 0; }
.auth-brand .ab-mid { display: none; }
.auth-form { padding: 26px 22px 22px; }
}
/* ---------------- 权限管理 ---------------- */
.rbac-menu-th { font-size: 11px !important; white-space: nowrap; }
.rbac-role { min-width: 138px; }
/* 权限矩阵列多,收紧内边距,避免 1280 宽时操作列盖住「用户」列 */
.tbl-tight th, .tbl-tight td { padding-left: 8px; padding-right: 8px; }
.rbac-role b { font-size: 13px; }
.rbac-role span { font-size: 11px; color: var(--muted); }
.rbac-role .desc { display: block; margin-top: 3px; }
.staff-note { max-width: 190px; font-size: 12px; color: var(--muted); }
.tag-mini.builtin { --c: var(--primary); }
.tag-mini.warn { --c: var(--warning); }
/* ---------------- main ---------------- */
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.topbar {
position: sticky; top: 0; z-index: var(--z-sticky);
display: flex; align-items: center; justify-content: space-between; gap: 16px;
padding: 12px var(--views-pad-x);
background: var(--surface-translucent);
backdrop-filter: blur(8px);
border-bottom: 1px solid var(--border);
}
.period-bar { display: flex; align-items: center; gap: 8px; }
.seg { display: flex; background: var(--surface-sunken); border-radius: var(--radius-md); padding: 3px; }
.seg-btn {
border: 0; background: transparent; padding: 5px 14px; border-radius: var(--radius-sm);
cursor: pointer; color: var(--text-2); font-size: 13px;
}
.seg-btn.active { background: var(--panel); color: var(--primary); font-weight: 600; box-shadow: var(--shadow-sm); }
/* 单选卡片:二选一、选中后下方直接出对应按钮(更新录入的写入方式) */
.radio-row { display: flex; gap: 10px; flex-wrap: wrap; }
.radio {
flex: 1 1 min(300px, 100%); display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-md);
background: var(--panel); font-size: 13px; cursor: pointer;
}
.radio input { accent-color: var(--primary); margin: 0; flex: none; }
.radio b { font-weight: 600; }
.radio .radio-tip { font-size: 12px; color: var(--muted); }
.radio:has(input:checked) { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 5%, var(--panel)); }
.nav-arrow {
display: inline-grid; place-items: center;
width: var(--ctrl-h); height: var(--ctrl-h); border-radius: var(--radius-sm); border: 1px solid var(--border);
background: var(--panel); cursor: pointer; color: var(--text-2); padding: 0;
}
.nav-arrow .ic { width: 15px; height: 15px; }
.nav-arrow:hover { border-color: var(--border-strong); color: var(--text); }
.period-select {
height: var(--ctrl-h); border: 1px solid var(--border); border-radius: var(--radius-sm);
padding: 0 10px; background: var(--panel); min-width: min(216px, 46vw); cursor: pointer;
}
.period-hint { color: var(--muted); font-size: 12px; margin-left: 4px; }
/* 顶栏的周期口径提示可能较长:限宽省略,别把搜索框挤走 */
.period-bar .period-hint {
min-width: 0; max-width: 34vw; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis;
}
@media (max-width: 1180px) { .period-bar .period-hint { display: none; } }
.topbar-right { display: flex; gap: 10px; align-items: center; }
.search {
height: var(--ctrl-h); border: 1px solid var(--border); border-radius: var(--radius-sm);
padding: 0 12px; width: min(220px, 42vw); min-width: 0; background: var(--panel);
}
.search:focus, .period-select:focus { outline: 2px solid var(--focus); outline-offset: 1px; border-color: var(--primary); }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
height: var(--ctrl-h); padding: 0 14px; border-radius: var(--radius-sm); border: 1px solid var(--border);
background: var(--panel); cursor: pointer; color: var(--text-2); white-space: nowrap;
}
.btn .ic { width: 14px; height: 14px; }
.btn:hover { border-color: var(--border-strong); color: var(--text); }
.btn.primary { background: var(--primary); border-color: var(--primary); color: var(--text-inverse); font-weight: 600; }
.btn.primary:hover { background: var(--primary-hover); }
.btn.ghost { background: transparent; }
.btn.sm { height: var(--ctrl-h-sm); padding: 0 11px; font-size: 12px; border-radius: var(--radius-sm); }
.btn.sm .ic { width: 12px; height: 12px; }
.btn.danger { color: var(--danger); }
.btn.danger:hover { border-color: var(--danger-border); background: var(--danger-soft); }
/* 危险确认弹窗的主按钮:实心红,别和「取消」长得太像 */
.btn.danger.solid { background: var(--danger); border-color: var(--danger); color: var(--text-inverse); font-weight: 600; }
.btn.danger.solid:hover { background: var(--danger-strong); border-color: var(--danger-strong); }
.btn:disabled { opacity: .5; cursor: not-allowed; }
.icon-btn {
display: inline-grid; place-items: center; border: 0; background: transparent;
cursor: pointer; color: var(--muted); padding: 5px; border-radius: var(--radius-sm);
}
.icon-btn .ic { width: 16px; height: 16px; }
.icon-btn:hover { background: var(--panel-2); color: var(--text); }
.icon-btn.sm { width: var(--ctrl-h-sm); height: var(--ctrl-h-sm); padding: 0; border-radius: var(--radius-sm); }
.icon-btn.sm .ic { width: 15px; height: 15px; }
.icon-btn.xs { width: var(--ctrl-h-xs); height: var(--ctrl-h-xs); padding: 0; border-radius: var(--radius-sm); }
.icon-btn.xs .ic { width: 13px; height: 13px; }
.icon-btn.danger:hover { background: var(--danger-soft); color: var(--danger); }
/* 表格行内操作:平时压灰,指针落到这一行才提亮 */
.row-ops { display: inline-flex; align-items: center; gap: 2px; opacity: .7; }
tr:hover .row-ops, .row-ops:focus-within { opacity: 1; }
/* 没有 hover 的设备上不能靠悬停才拿到操作 */
@media (hover: none) { .row-ops, .u-ops { opacity: 1; } }
.views { padding: var(--views-pad-y) var(--views-pad-x) 60px; min-width: 0; }
.hidden { display: none !important; }
/* ---------------- cards ---------------- */
.card {
background: var(--panel); border: 1px solid var(--border);
border-radius: var(--radius); box-shadow: var(--shadow);
}
.card-head {
padding: 13px 16px; border-bottom: 1px solid var(--border);
display: flex; align-items: center; justify-content: space-between; gap: 10px;
flex-wrap: wrap;
}
.card-head h3 { margin: 0; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
.card-head h3 .t, .card-head .period-hint, .card-head .switch { white-space: nowrap; }
/* 统一计数 chip:卡头、分组标题共用一颗灰底小圆牌 */
.card-head h3 .cnt { font-size: 11px; font-weight: 600; color: var(--text-2); background: var(--surface-sunken); border-radius: var(--radius-pill); padding: 1px 7px; }
.card-body { padding: 16px; }
.grid { display: grid; gap: var(--card-gap); }
.grid.kpi {
grid-template-columns: repeat(auto-fit, minmax(min(180px, 100%), 1fr));
background: none; border: 0; box-shadow: none; padding: 0; border-radius: 0;
}
.grid.g2 { grid-template-columns: 1.35fr 1fr; }
.grid.g2e { grid-template-columns: 1fr 1fr; }
@media (max-width: 1180px) { .grid.g2, .grid.g2e { grid-template-columns: 1fr; } }
/* KPI:图标底板在左,数字用重点色 */
.kpi {
display: grid; grid-template-columns: auto 1fr; column-gap: 12px; align-items: center;
background: var(--panel); border: 1px solid var(--border);
border-radius: var(--radius); padding: 14px 16px; box-shadow: var(--shadow);
}
.kpi > .ic-badge { grid-row: 1 / span 3; }
.kpi > .k-label, .kpi > .k-value, .kpi > .k-foot { grid-column: 2; min-width: 0; }
.kpi .k-label { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kpi .k-value { font-size: 25px; font-weight: 700; margin-top: 4px; letter-spacing: -.5px; color: var(--c, var(--text)); font-variant-numeric: tabular-nums; }
.kpi .k-value.sm { font-size: 22px; }
.kpi .k-value.xs { font-size: 18px; }
.kpi .k-foot { font-size: 11px; color: var(--muted); margin-top: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kpi.accent-blue { --c: var(--primary); }
.kpi.accent-violet { --c: var(--violet); }
.kpi.accent-green { --c: var(--success); }
.kpi.accent-amber { --c: var(--warning); }
.kpi.accent-red { --c: var(--danger); }
/* ---------------- 统计区块的上下留白(各页统一) ----------------
口径:统计行上方一律 24px、下方一律 20px,四个页面看着一样。
· 贴在页面顶部的(工作看板 / 人力资源):.views 的上内边距先垫 20px,这里再补 4px;
· 在卡片里的(定制项目 · 项目总览 / 本周进展):卡头底下自己出满 24px。
新增统计行请只挂 .kpi-row,不要再写行内 margin / padding。 */
.grid.kpi.kpi-row { margin: 4px 0 20px; }
.card > .grid.kpi.kpi-row { margin: 24px 0 20px; padding: 0 16px; }
.card > .grid.kpi.kpi-row:last-child { margin-bottom: 24px; }
/* 表单里周期的口径说明 */
.period-note { margin-top: 6px; }
/* ---------------- board ---------------- */
.board-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }
.chip {
display: inline-flex; align-items: center; gap: 6px;
padding: 4px 11px; border-radius: var(--radius-pill); font-size: 12px;
background: var(--panel); border: 1px solid var(--border); color: var(--text-2); cursor: pointer;
}
.chip .ic { width: 13px; height: 13px; }
.chip.active { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.chip.active .ic { color: var(--primary); }
/* 定制项目页签:卡片外的文件夹式页签,选中项压住卡片顶边,和下方内容区连成一块 */
.ctabs { display: flex; align-items: flex-end; gap: 2px; padding: 0 14px; position: relative; z-index: 2; overflow-x: auto; scrollbar-width: thin; } /* 局部层叠:只要压住卡片顶边,不参与全局层级 */
.ctab {
border: 1px solid transparent; border-bottom: 0; background: transparent;
color: var(--muted); font-size: 13px; padding: 8px 18px; cursor: pointer;
border-radius: var(--radius-md) 10px 0 0;
}
.ctab:hover { color: var(--primary); background: var(--primary-soft); }
.ctab.active {
background: var(--panel); border-color: var(--border);
color: var(--primary); font-weight: 600; margin-bottom: -1px;
}
.star { display: inline-flex; color: var(--border-strong); line-height: 1; user-select: none; cursor: pointer; flex: none; }
.star .ic { width: 14px; height: 14px; }
.star.on { color: var(--star); }
.star.on .ic { fill: currentColor; }
/* 状态与标签的唯一底板算法:调用方只注入 --c(状态色 / 分类色),
文字色由 --c 与正文色混合派生,保证浅色系状态色也能读;底色 + 文字 + 图标三重线索。 */
.pill, .tag-mini, .arch-badge {
background: color-mix(in srgb, var(--c) 12%, var(--panel));
color: color-mix(in srgb, var(--c) 58%, var(--text));
}
.pill {
--c: var(--muted);
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; padding: 2px 8px; border-radius: var(--radius-pill); line-height: 1.6; font-weight: 500;
white-space: nowrap;
}
.pill .ic { width: 12px; height: 12px; }
.tag-mini {
--c: var(--text-2);
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-size: 11px; padding: 2px 7px; border-radius: var(--radius-sm);
}
.tag-mini .ic { width: 12px; height: 12px; }
.progress { height: 6px; background: var(--surface-sunken); border-radius: var(--radius-pill); overflow: hidden; margin-top: 10px; }
.progress > i { display: block; height: 100%; background: var(--primary); border-radius: var(--radius-pill); transition: width var(--dur-3) var(--ease); }
.progress-label { display: flex; justify-content: space-between; font-size: 11px; color: var(--muted); margin-top: 6px; }
/* 备注块(看板右栏 / 抽屉详情共用;原阶段看板 kanban 样式已随 tab 下线删除) */
.kcard-remark { font-size: 11px; color: var(--muted); margin-top: 6px; line-height: 1.5; }
.empty { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 40px 16px; text-align: center; color: var(--muted); font-size: 13px; }
.empty .ic-lg { color: var(--border-strong); }
/* ---------------- tables ---------------- */
table.tbl { width: 100%; border-collapse: separate; border-spacing: 0; } /* separate:让操作列的 sticky 生效(collapse 下部分内核不吸边) */
table.tbl th, table.tbl td {
padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: middle;
}
table.tbl th { font-size: 12px; color: var(--muted); font-weight: 500; background: var(--panel-2); position: sticky; top: 0; white-space: nowrap; }
table.tbl tbody tr:hover { background: var(--surface-hover); }
table.tbl td.num, table.tbl th.num { text-align: right; font-variant-numeric: tabular-nums; }
.tbl-wrap { max-height: min(620px, 72vh); overflow: auto; overscroll-behavior-x: contain; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
.tbl-wrap:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
.nowrap { white-space: nowrap; }
/* 截断的关键文本:hover 有 title,键盘/触屏聚焦即可展开全文(NEX 06.3)*/
.trunc {
display: inline-block; max-width: 260px; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; vertical-align: bottom; border-radius: var(--radius-sm);
}
.trunc:focus { white-space: normal; word-break: break-all; overflow: visible; max-width: min(420px, 60vw); }
/* ---------------- 列表分页(全站统一,默认 10 条/页) ---------------- */
.pager {
display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end;
padding: 10px 14px; border-top: 1px solid var(--border);
}
.pager .pg-info { font-size: 12px; color: var(--muted); }
.pager .pg-btns { display: flex; align-items: center; gap: 4px; }
.pg-btn {
min-width: 28px; height: var(--ctrl-h-sm); padding: 0 7px;
border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--panel);
color: var(--text-2); font-size: 12px; cursor: pointer;
}
.pg-btn:hover:not(:disabled):not(.active) { border-color: var(--border-strong); color: var(--text); }
.pg-btn.active { background: var(--primary); border-color: var(--primary); color: var(--text-inverse); font-weight: 600; }
.pg-btn:disabled { opacity: .45; cursor: not-allowed; }
.pg-gap { font-size: 12px; color: var(--muted); padding: 0 2px; }
.pager .pg-size { height: var(--ctrl-h-sm); }
.inp, .sel {
height: var(--ctrl-h); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 0 9px; background: var(--panel); max-width: 100%;
}
textarea.inp { height: auto; padding: 8px 10px; line-height: 1.6; }
.inp:focus, .sel:focus { outline: 2px solid var(--focus); outline-offset: 1px; border-color: var(--primary); }
/* 表格里的数字输入(年度目标等):右对齐、等宽数字,别把行高撑开 */
.num-inp { width: 100px; height: var(--ctrl-h-sm); text-align: right; font-variant-numeric: tabular-nums; }
/* ---------------- drawer ---------------- */
.drawer-mask { position: fixed; inset: 0; background: var(--overlay-mask); opacity: 0; pointer-events: none; transition: opacity var(--dur-2) var(--ease); z-index: var(--z-mask); }
.drawer-mask.open { opacity: 1; pointer-events: auto; }
.drawer {
position: fixed; top: 0; right: 0; bottom: 0; width: 620px; max-width: 92vw;
background: var(--panel); z-index: var(--z-drawer); transform: translateX(100%);
transition: transform var(--dur-3) var(--ease), visibility 0s linear var(--dur-3);
display: flex; flex-direction: column; box-shadow: var(--shadow-lg);
visibility: hidden;
}
.drawer.open { transform: translateX(0); visibility: visible; transition: transform var(--dur-3) var(--ease), visibility 0s; }
.drawer-head { padding: 14px 20px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; gap: 12px; }
/* 标准对话框标题栏:标题在左,操作按钮成排在右,关闭图标在最右 */
.drawer-head-text { flex: 1; min-width: 0; }
.drawer-head .dlg-title { margin: 0; font-size: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; gap: 8px; }
/* 多负责人 / 团队成员编辑器:人名下拉横向排开、自动换行,名单不分主次 */
.form-row.top { align-items: start; }
.people-rows { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.people-row { display: inline-flex; align-items: center; gap: 2px; }
.people-del { width: var(--ctrl-h-sm); padding: 0; justify-content: center; color: var(--muted); }
.people-del:hover { color: var(--danger); }
/* 列表里的负责人列:负责人对等排成一排,不分主次 */
.people-cell { display: flex; flex-wrap: nowrap; gap: 4px; }
.btn-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: flex-end; }
.drawer-sub { font-size: 12px; color: var(--muted); margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.drawer-body { padding: 18px 20px 40px; overflow: auto; flex: 1; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
.sec { margin-bottom: 22px; }
.sec-title { margin-top: 0; font-size: 12px; color: var(--muted); letter-spacing: .5px; margin-bottom: 10px; display: flex; align-items: center; gap: 7px; }
.sec-title::after { content: ""; flex: 1; height: 1px; background: var(--border); }
.form-row { display: grid; grid-template-columns: 88px 1fr; gap: 10px; align-items: center; margin-bottom: 10px; }
.form-row > label, .form-row > .fld-label, .kv > label, .kv > .fld-label { font-size: 12px; color: var(--muted); }
/* 网格子项默认 min-width:auto,交付环节这类步骤条会把抽屉整行撑出横向滚动;
归零后由步骤条自己的 overflow-x 接管,表单标签保持不动 */
.form-row > div { min-width: 0; }
.inline-fields { display: flex; gap: 8px; flex-wrap: wrap; }
/* 卡头(子 header)内的两块:筛选 chip 紧跟标题,操作按钮统一靠最右 */
.head-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.head-tools {
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
justify-content: flex-end; margin-left: auto;
}
.head-tools .btn.sm, .head-tools .inp, .head-tools .sel, .head-tools .search { height: var(--ctrl-h-sm); }
.head-tools .inp, .head-tools .sel, .head-tools .search { font-size: 12.5px; }
.head-tools .switch { font-size: 12px; padding: 0; }
.sel.xs { height: var(--ctrl-h-sm); padding: 0 6px; font-size: 12px; }
/* 详情(只读)/ 修改(编辑)分离:只读值、区块操作条 */
.form-row > .ro { font-size: 13px; color: var(--text); line-height: 1.7; }
.sec-actions {
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
margin-top: 14px; padding: 9px 11px;
background: var(--panel-2); border-radius: var(--radius-md);
}
.sec-hint { font-size: 11.5px; color: var(--muted); margin-left: auto; }
.wk-i-name .star, .wk-head-title .star, .drawer-head .dlg-title .star { margin-right: 4px; vertical-align: -2px; }
.star.readonly { cursor: default; }
.star.readonly:not(.on) { opacity: .35; }
.upd-item { border-radius: var(--radius-md); padding: 11px 13px; margin-bottom: 10px; background: var(--panel-2); }
.upd-item .u-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; }
.upd-item .u-task { font-weight: 600; font-size: 13px; }
.upd-item .u-body { font-size: 12.5px; color: var(--text-2); line-height: 1.7; white-space: pre-wrap; word-break: break-word; }
.upd-item .u-risk { display: flex; align-items: flex-start; gap: 6px; margin-top: 8px; font-size: 12px; color: var(--warning); background: var(--warning-soft); border-radius: var(--radius-sm); padding: 6px 9px; }
.upd-item .u-risk .ic { margin-top: 2px; color: var(--warning); }
.upd-item .u-next { display: flex; align-items: flex-start; gap: 6px; margin-top: 6px; font-size: 12px; color: var(--primary); background: var(--primary-soft); border-radius: var(--radius-sm); padding: 6px 9px; }
.upd-item .u-next .ic { margin-top: 2px; }
/* 条目右上角的「修改 / 删除」:平时不占视觉,指针进条目才显现 */
.u-ops { display: inline-flex; gap: 2px; margin-left: auto; opacity: .7; transition: opacity var(--dur-1) var(--ease); }
.upd-item:hover .u-ops, .u-ops:focus-within { opacity: 1; }
.feed-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 12px; }
.feed-bar .seg-btn { padding: 4px 10px; font-size: 12px; }
.feed-chips { display: flex; gap: 6px; flex-wrap: wrap; }
.feed-bar .chip { padding: 3px 9px; }
.feed-pager { display: flex; gap: 4px; }
.feed-ops { display: flex; gap: 8px; margin-left: auto; }
.nav-arrow.sm { width: var(--ctrl-h-xs); height: var(--ctrl-h-xs); border-radius: var(--radius-sm); }
.nav-arrow.sm .ic { width: 13px; height: 13px; }
.nav-arrow.sm:disabled { opacity: .45; cursor: not-allowed; }
.feed-hd { display: flex; align-items: center; gap: 10px; font-size: 12.5px; color: var(--text-2); margin: 14px 0 8px; padding-bottom: 5px; border-bottom: 1px solid var(--border); }
.feed-hd b { font-size: 13px; color: var(--text); }
.feed-hd .feed-cnt { margin-left: auto; font-size: 11.5px; color: var(--muted); }
.feed-sub { font-size: 12px; color: var(--muted); margin: 8px 0 6px; }
.timeline-row { display: flex; align-items: center; gap: 10px; padding: 7px 0; border-bottom: 1px solid var(--border); }
.timeline-row .t-label { width: 110px; font-size: 12px; color: var(--text-2); flex: 0 0 110px; }
.timeline-row .t-bar { flex: 1; }
.timeline-row .t-val { width: 46px; text-align: right; font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }
.bullet-list { margin: 0; padding-left: 18px; font-size: 12.5px; color: var(--text-2); line-height: 1.8; }
.bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 9px; }
.bar-row .b-name { width: 150px; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar-row .b-track { flex: 1; height: 8px; background: var(--surface-sunken); border-radius: var(--radius-pill); overflow: hidden; }
.bar-row .b-track > i { display: block; height: 100%; border-radius: var(--radius-pill); }
.bar-row .b-val { width: 44px; text-align: right; font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }
/* ---------------- intake ---------------- */
.step { display: flex; gap: 10px; align-items: center; margin-bottom: 6px; }
.step-no { width: 22px; height: 22px; border-radius: 50%; background: var(--primary-soft); color: var(--primary); display: grid; place-items: center; font-size: 12px; font-weight: 700; flex: 0 0 22px; }
.step-title { font-weight: 600; font-size: 13px; }
.big-textarea { width: 100%; min-height: min(190px, 40vh); resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; }
.preview-box { border: 1px solid var(--border); border-radius: var(--radius-md); padding: 14px; background: var(--panel-2); }
.kv { display: grid; grid-template-columns: 92px 1fr; gap: 8px; align-items: center; margin-bottom: 8px; }
.notice { display: flex; align-items: flex-start; gap: 7px; font-size: 12px; padding: 9px 11px; border-radius: var(--radius-md); margin-bottom: 12px; line-height: 1.6; }
.notice .ti { width: 14px; height: 14px; margin-top: 2px; color: currentColor; }
.notice.warn { background: var(--warning-soft); color: var(--warning); }
.notice.info { background: var(--primary-soft); color: var(--info-text); }
.notice.err { background: var(--danger-soft); color: var(--danger-strong); }
/* ---------------- toast ---------------- */
.toast {
position: fixed; left: 50%; bottom: 34px; transform: translate(-50%, 20px);
max-width: min(92vw, 520px); text-align: center; pointer-events: none;
background: var(--surface-inverse); color: var(--text-inverse); padding: 10px 18px; border-radius: var(--radius-md);
font-size: 13px; opacity: 0; pointer-events: none; transition: opacity var(--dur-2) var(--ease), transform var(--dur-2) var(--ease); z-index: var(--z-toast);
}
.toast.show { opacity: 1; transform: translate(-50%, 0); }
.spinner { display: inline-block; width: 13px; height: 13px; margin-right: 6px; border: 2px solid color-mix(in srgb, currentColor 30%, transparent); border-top-color: currentColor; border-radius: 50%; animation: spin .7s linear infinite; vertical-align: -2px; }
@keyframes spin { to { transform: rotate(360deg); } }
/* ---------------- modal ---------------- */
.modal-mask {
position: fixed; inset: 0; background: var(--overlay-mask);
display: none; align-items: center; justify-content: center; padding: 24px; z-index: var(--z-modal);
}
.modal-mask.open { display: flex; }
.modal {
width: 580px; max-width: 100%; max-height: 88vh; overflow: auto;
background: var(--panel); border-radius: var(--radius);
box-shadow: var(--shadow-xl); animation: pop var(--dur-1) var(--ease);
}
@keyframes pop { from { transform: translateY(8px) scale(.985); opacity: .5; } }
.modal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 13px 18px; border-bottom: 1px solid var(--border); }
.modal-head .dlg-title { margin: 0; font-size: 15px; }
.modal-body { padding: 16px 18px 6px; }
.modal-foot {
display: flex; justify-content: flex-end; gap: 10px; padding: 14px 18px;
border-top: 1px solid var(--border); margin-top: 14px;
position: sticky; bottom: 0; background: var(--panel);
}
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 18px; }
.form-grid .full { grid-column: 1 / -1; }
.arch-badge { --c: var(--muted); font-size: 11px; padding: 1px 7px; border-radius: var(--radius-pill); white-space: nowrap; flex: none; }
/* 操作列固定在表格右侧:横向滚动时改名/归档/删除始终可见(项目管理、定制项目共用) */
table.tbl th.col-ops, table.tbl td.col-ops {
position: sticky; right: 0; background: var(--panel); box-shadow: inset 1px 0 0 var(--border);
}
table.tbl th.col-ops { background: var(--panel-2); z-index: 3; } /* 表头压住同列单元格,局部层叠 */
table.tbl tbody tr:hover td.col-ops { background: var(--surface-hover); }
table.tbl td.col-ops .btn.sm { padding: 0 7px; } /* 操作列按钮收紧,避免把整张表撑出横向滚动 */
/* ---------------- 周看板:左栏总览 + 右栏详情 ---------------- */
.wk-split { display: grid; grid-template-columns: 320px 1fr; gap: 16px; align-items: start; }
@media (max-width: 1180px) { .wk-split { grid-template-columns: 1fr; } }
.wk-left { padding: 10px; max-height: calc(100vh - var(--h-topbar) - var(--sp-8) - 48px); overflow: auto; position: sticky; top: calc(var(--h-topbar) + var(--sp-4)); }
@media (max-width: 1180px) { .wk-left { position: static; max-height: none; } }
.wk-right { padding: 16px 18px; min-width: 0; }
.wk-group { margin-bottom: 6px; }
.wk-group-head {
margin: 0;
display: flex; align-items: center; gap: 6px;
font-size: 12px; color: var(--muted); letter-spacing: .4px;
padding: 8px 6px 6px; position: sticky; top: 0; background: var(--panel); z-index: 1;
}
.wk-group-head .ic { width: 14px; height: 14px; }
.wk-group-head .cnt { font-size: 11px; background: var(--surface-sunken); color: var(--text-2); border-radius: var(--radius-pill); padding: 0 6px; }
.wk-group-foot { margin-left: auto; font-size: 11px; }
/* 列表行:无边框,选中时用状态色淡染 */
.wk-item {
display: block; width: 100%; text-align: left; border: 0; font: inherit; color: inherit;
border-radius: var(--radius-md); padding: 9px 10px; margin-bottom: 3px;
cursor: pointer; background: transparent; transition: background var(--dur-1) var(--ease);
}
.wk-item:hover { background: var(--panel-2); }
.wk-item:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
.wk-item.active {
background: var(--primary-soft);
background: color-mix(in srgb, var(--c, var(--primary)) 10%, var(--panel));
/* 选中不只靠底色:左侧 3px 色条 + 加粗,键盘与辅助技术同样能分辨 */
box-shadow: inset 3px 0 0 var(--c, var(--primary));
font-weight: 600;
}
.wk-item.active .wk-i-name { color: var(--c, var(--text)); }
.wk-i-top { display: flex; align-items: center; gap: 7px; }
.wk-i-ic { display: inline-flex; color: var(--c, var(--muted)); flex: none; }
.wk-i-ic .ic { width: 15px; height: 15px; }
.wk-i-name { font-size: 13px; font-weight: 600; line-height: 1.4; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wk-i-meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-top: 7px; padding-left: 22px; }
.wk-i-sub { display: block; margin-top: 6px; font-size: 11px; color: var(--muted); line-height: 1.5; padding-left: 22px; }
/* 详情面板头 = 子 header:左侧标题与元信息,右侧放这个面板自己的操作按钮 */
.wk-head {
display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap;
margin-bottom: 20px; padding-bottom: 14px; border-bottom: 1px solid var(--border);
}
.wk-head-main { flex: 1 1 320px; min-width: 0; }
.wk-head-ops { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: flex-end; margin-left: auto; }
.wk-head-title { display: flex; align-items: center; gap: 9px; font-size: 16px; font-weight: 600; line-height: 1.4; }
.wk-head-title .ic-badge { width: 28px; height: 28px; border-radius: var(--radius-sm); }
.wk-head-title .ic-badge > .ic { width: 16px; height: 16px; }
.wk-head .wk-i-meta, .wk-head .wk-i-sub { padding-left: 0; }
/* 归档 / 停用的行:降透明度但有文字徽章兜底,不只靠变淡 */
.is-archived { opacity: .62; }
/* 交付环节步骤条:入库 → 签单 → 交付 → 验收 → 计收 */
.pipe { display: flex; align-items: flex-start; gap: 6px; overflow-x: auto; padding-bottom: 4px; }
.pipe-step {
/* 132px = 日期框(含选择器图标)的完整宽度;放不下交给 .pipe 横向滚动 */
flex: 1 1 132px; min-width: 132px; border: 1px solid var(--border); border-radius: var(--radius-md);
padding: 8px 9px; background: var(--panel-2);
}
.pipe-step.done { background: var(--panel); }
.pipe-step.now { background: color-mix(in srgb, var(--c, var(--primary)) 10%, var(--panel)); }
.pipe-name { display: flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; color: var(--text-2); margin-bottom: 6px; }
.pipe-step.done .pipe-name, .pipe-step.now .pipe-name { color: var(--c, var(--text-2)); }
.pipe-name .ic { width: 13px; height: 13px; color: var(--c, var(--muted)); }
.pipe-step .inp { width: 100%; min-width: 0; height: var(--ctrl-h-sm); font-size: 12px; }
.pipe-date { font-size: 12px; color: var(--text-2); min-width: 80px; }
.pipe-date.none { color: var(--muted); }
.pipe-arrow { align-self: center; color: var(--muted); padding-top: 12px; flex: none; }
.pipe-arrow .ic { width: 14px; height: 14px; }
/* 小字段:金额补录等内联输入 */
.field-mini { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
/* 主导航分组标题:业务四个不给标题,只给「支撑」组(index.html) */
.nav-label { font-size: 11px; color: var(--muted); letter-spacing: .6px; padding: 14px 10px 4px; }
/* 角色多选(用户弹窗) */
.check-row { display: flex; flex-wrap: wrap; gap: 8px 14px; padding: 4px 0; }
.check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text); cursor: pointer; }
.check input { width: 15px; height: 15px; accent-color: var(--primary); cursor: pointer; }
.check input:disabled { cursor: not-allowed; }
.check input:disabled + * { color: var(--muted); }
/* =================================================================
NEX 组件层:页面抬头 / 弹层 / 加载态 / 窄屏与动效
—— 只复用上面的语义 Token,不新增裸设计值
================================================================= */
/* ---------------- 页面抬头(同类页面统一:标题 + 说明 + 主操作)---------------- */
.tabpanel { min-width: 0; }
.page-head {
display: flex; align-items: flex-end; justify-content: space-between; gap: var(--sp-4);
flex-wrap: wrap; margin: 0 0 var(--sp-4);
}
.page-head-text { min-width: 0; }
.page-title { margin: 0; font-size: 17px; font-weight: 600; letter-spacing: -.1px; }
.page-desc { margin: 3px 0 0; font-size: 12px; color: var(--muted); line-height: 1.5; }
.page-actions { display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; }
@media (max-width: 640px) {
.page-head { align-items: flex-start; margin-bottom: var(--sp-3); }
.page-title { font-size: 16px; }
}
/* ---------------- 链接式按钮(原 <a href="javascript:;">,语义回到 button)---------------- */
.link-btn {
border: 0; background: none; padding: 0; margin: 0; font: inherit; color: var(--text);
cursor: pointer; text-align: left; border-radius: var(--radius-sm);
}
.link-btn:hover { color: var(--primary); text-decoration: underline; text-underline-offset: 2px; }
/* ---------------- 表头排序(可键盘操作 + aria-sort)---------------- */
.th-sort {
display: inline-flex; align-items: center; gap: 4px; border: 0; background: none; padding: 0;
font: inherit; color: inherit; cursor: pointer; border-radius: var(--radius-sm);
}
.th-sort:hover { color: var(--text); }
.th-sort .sort-ind { opacity: .35; font-size: 10px; line-height: 1; }
th[aria-sort="ascending"] .sort-ind, th[aria-sort="descending"] .sort-ind { opacity: 1; }
th[aria-sort="ascending"], th[aria-sort="descending"] { color: var(--primary); }
/* ---------------- 选中态不只靠颜色:chip / 分段 / 页签 / 页码 ---------------- */
.chip[aria-pressed="true"] { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
.chip[aria-pressed="true"] .ic { color: var(--primary); }
.seg-btn[aria-pressed="true"] { background: var(--panel); color: var(--primary); font-weight: 600; box-shadow: var(--shadow-sm); }
.ctab[aria-selected="true"] { background: var(--panel); border-color: var(--border); color: var(--primary); font-weight: 600; margin-bottom: -1px; }
.pg-btn[aria-current="page"] { background: var(--primary); border-color: var(--primary); color: var(--on-primary); font-weight: 600; }
[role="tablist"] { display: flex; align-items: flex-end; gap: 2px; }
/* ---------------- 抽屉 / 弹窗标题(对话框内的 h2)---------------- */
.dlg-title { margin: 0; font-size: 16px; font-weight: 600; min-width: 0; }
.modal .dlg-title { font-size: 15px; }
#drawer[role="dialog"], .modal[role="dialog"] { outline: none; }
/* ---------------- 加载态:占位与真实卡片同尺寸,避免内容到位时整页跳动(07.1)---------------- */
.loading-block { display: flex; flex-direction: column; gap: var(--sp-3); }
.sk { background: var(--surface-sunken); border-radius: var(--radius-sm); position: relative; overflow: hidden; }
.sk::after {
content: ""; position: absolute; inset: 0; transform: translateX(-100%);
background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--panel) 70%, transparent), transparent);
animation: sk-sweep 1.1s var(--ease) infinite;
}
@keyframes sk-sweep { to { transform: translateX(100%); } }
.sk-line { height: 12px; }
.sk-title { height: 22px; width: 200px; }
.sk-card { height: 76px; }
.sk-row { height: 38px; }
/* ---------------- 小屏导航:侧栏转抽屉,给内容让位(03.3)---------------- */
.nav-toggle { display: none; }
.nav-mask { display: none; }
@media (max-width: 1100px) {
.app { --sidebar-w: 0px; }
.nav-toggle {
display: inline-grid; place-items: center; width: var(--ctrl-h); height: var(--ctrl-h);
border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--panel);
color: var(--text-2); cursor: pointer; flex: none; padding: 0;
}
.nav-toggle:hover { border-color: var(--border-strong); color: var(--text); }
.sidebar {
position: fixed; left: 0; top: 0; bottom: 0; height: 100dvh;
width: min(280px, 84vw); flex: none; z-index: var(--z-drawer);
transform: translateX(-100%); transition: transform var(--dur-3) var(--ease);
box-shadow: var(--shadow-xl); overflow-y: auto;
}
.app.nav-open .sidebar { transform: none; }
.nav-mask {
display: block; position: fixed; inset: 0; z-index: var(--z-mask);
background: var(--overlay-mask); opacity: 0; pointer-events: none; transition: opacity var(--dur-2) var(--ease);
}
.app.nav-open .nav-mask { opacity: 1; pointer-events: auto; }
/* 小屏不沿用桌面「收拢成图标」那一态:抽屉里必须能看清菜单名称 */
.app.nav-folded { --sidebar-w: 0px; }
.app.nav-folded .brand { justify-content: flex-start; }
.app.nav-folded .brand-text, .app.nav-folded .user-chip .u-text { display: flex; }
.app.nav-folded .nav-item .nl { display: inline; }
.app.nav-folded .user-chip .ic { display: inline-flex; }
.app.nav-folded .nav-item { justify-content: flex-start; gap: 10px; padding: 9px 10px; }
.app.nav-folded .user-chip { justify-content: flex-start; padding: 7px 8px; }
.app.nav-folded .nav-label { font-size: 11px; height: auto; background: none; margin: 14px 10px 4px; padding: 0; }
.app.nav-folded .nav-item[data-tip]:hover::after { content: none; }
.app.nav-folded .sidebar { z-index: var(--z-drawer); }
.nav-fold { display: none !important; }
}
/* <=900:顶栏与卡头工具栏折行,次要操作让位(03.4)*/
@media (max-width: 900px) {
.topbar { flex-wrap: wrap; gap: var(--sp-2); padding: 10px var(--sp-4); }
.period-bar { flex: 1 1 auto; min-width: 0; }
.period-select { min-width: 0; flex: 1 1 auto; }
.topbar-right { flex: 1 1 100%; }
.topbar-right .search { flex: 1 1 auto; width: auto; min-width: 0; }
.views { padding: var(--sp-4) var(--sp-4) 48px; }
.head-tools { margin-left: 0; width: 100%; justify-content: flex-start; }
.card > .grid.kpi.kpi-row { padding: 0 var(--sp-3); }
.wk-left { max-height: none; position: static; }
.drawer { width: 100%; max-width: 100%; }
.drawer-head { flex-wrap: wrap; }
.drawer-actions-row, .btn-bar { width: 100%; justify-content: flex-end; }
}
/* <=640:单列表单、弹层满屏、触控目标放大 */
@media (max-width: 640px) {
.views { padding: var(--sp-3) var(--sp-3) 48px; }
.form-grid { grid-template-columns: 1fr; }
.form-row { grid-template-columns: 1fr; gap: var(--sp-1); }
.form-row.top { align-items: start; }
.kv { grid-template-columns: 1fr; gap: 2px; }
.modal-mask { padding: 0; align-items: flex-end; }
.modal { width: 100%; max-width: 100%; max-height: 92dvh; border-radius: var(--radius-lg) var(--radius-lg) 0 0; }
.modal-foot { position: sticky; bottom: 0; }
.grid.kpi { grid-template-columns: repeat(auto-fit, minmax(148px, 1fr)); }
.ctabs { overflow-x: auto; padding: 0 var(--sp-2); }
.ctab { flex: none; }
.pipe-step { flex: 1 1 150px; min-width: 150px; }
.wk-i-meta, .wk-i-sub { padding-left: 0; }
.pager { justify-content: center; }
.feed-ops { margin-left: 0; width: 100%; }
.icon-btn, .nav-arrow, .pg-btn, .seg-btn, .chip, .nav-item { min-height: var(--touch); }
.icon-btn.xs, .nav-arrow.sm { min-height: 32px; min-width: 32px; }
.btn, .inp, .sel, .search, .period-select { min-height: var(--touch); }
table.tbl th, table.tbl td { padding: 9px 10px; }
}
/* ---------------- 尊重系统「减少动态效果」(06.7)---------------- */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: .01ms !important; animation-iteration-count: 1 !important;
transition-duration: .01ms !important; scroll-behavior: auto !important;
}
.sk::after { animation: none; }
}
/* ---------------- 高对比 / 强制颜色模式下的保底边界 ---------------- */
@media (forced-colors: active) {
.card, .kpi, .modal, .drawer, .sidebar, .inp, .sel, .btn { border: 1px solid CanvasText; }
.pill, .tag-mini, .arch-badge, .chip { border: 1px solid CanvasText; }
}

3878
web/package-lock.json generated 100755

File diff suppressed because it is too large Load Diff

37
web/package.json 100755
View File

@ -0,0 +1,37 @@
{
"name": "unis-manager-web",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "DMS管理平台前端(NEX 0.1.7 标准栈:React + TypeScript + Vite + Ant Design + Tailwind v4 + Zustand + React Router + Axios)",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@tiptap/extension-bold": "^3.34.0",
"@tiptap/extension-italic": "^3.34.0",
"@tiptap/extension-text-style": "^3.34.0",
"@tiptap/pm": "^3.34.0",
"@tiptap/react": "^3.34.0",
"@tiptap/starter-kit": "^3.34.0",
"antd": "^6.7.0",
"axios": "^1.21.1",
"dayjs": "^1.11.23",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.5",
"zustand": "^5.1.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.3.0",
"tailwindcss": "^4.3.5",
"typescript": "^7.0.2",
"vite": "^8.3.8"
}
}

52
web/src/App.tsx 100755
View File

@ -0,0 +1,52 @@
import { App as AntApp, ConfigProvider, Spin } from "antd";
import zhCN from "antd/locale/zh_CN";
import { useEffect, useMemo, useState } from "react";
import { RouterProvider } from "react-router-dom";
import { onUnauthorized } from "./api/client";
import { LoginGate } from "./components/LoginGate";
import { router } from "./router";
import { assertTokensMatch, buildAntdTheme } from "./theme/antd";
import { useMeta } from "./store/meta";
import { useSession } from "./store/session";
import { THEME_KEY, useUi } from "./store/ui";
/** 根组件:先验会话(登录门 / 应用外壳),登录后再拉全局字典与周期。
* ConfigProvider 把项目 token 交给 AntD;App 包住 message / modal 上下文(保持同一套反馈通道)。*/
export default function App() {
const theme = useUi((s) => s.theme);
const antdTheme = useMemo(() => buildAntdTheme(theme), [theme]);
const me = useSession((s) => s.me);
const checked = useSession((s) => s.checked);
const load = useSession((s) => s.load);
const [ready, setReady] = useState(false);
/* 主题落进 <html data-theme>:CSS 语义 token 整体换层;并按当前主题核对 AntD 色板(dev 才有输出)*/
useEffect(() => {
document.documentElement.dataset.theme = theme;
assertTokensMatch(theme);
try { localStorage.setItem(THEME_KEY, theme); } catch { /* 隐私模式存不下就算了:下次打开回到跟随系统 */ }
}, [theme]);
useEffect(() => { void load(); }, [load]);
useEffect(() => onUnauthorized(() => useSession.setState({ me: null })), []);
useEffect(() => {
if (!me) { setReady(false); return; }
Promise.all([useMeta.getState().ensureMeta(), useMeta.getState().ensurePeriods()])
.then(() => setReady(true))
.catch(() => setReady(true)); // 字典拉不到也进界面,视图里各自报错并可重试
}, [me]);
useEffect(() => { if (me) useUi.getState().set({ view: (location.pathname.split("/")[1] || "board") as never }); }, [me]);
return (
<ConfigProvider locale={zhCN} theme={antdTheme} autoInsertSpaceInButton={false}>
<AntApp>
{!checked
? <div className="boot"><Spin size="large" /></div>
: !me
? <LoginGate />
: !ready
? <div className="boot"><Spin size="large" /></div>
: <RouterProvider router={router} />}
</AntApp>
</ConfigProvider>
);
}

View File

@ -0,0 +1,80 @@
import axios, { AxiosError } from "axios";
import type { Query } from "../types/domain";
/** 统一错误:后端已把 422/500 翻成中文 detail(app/main.py),这里只搬运,不翻译。*/
export class ApiError extends Error {
status?: number;
constructor(message: string, status?: number) { super(message); this.name = "ApiError"; this.status = status; }
}
export const apiMsg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
export const http = axios.create({ baseURL: "/api", timeout: 60000 });
/* 会话过期只广播,由登录门接管(不整页跳转,保住用户已填的表单)*/
type Handler = () => void;
const unauthorized = new Set<Handler>();
export const onUnauthorized = (fn: Handler) => { unauthorized.add(fn); return () => { unauthorized.delete(fn); }; };
http.interceptors.response.use(
(r) => r,
(err: AxiosError<any>) => {
const status = err.response?.status;
if (status === 401) { unauthorized.forEach((f) => f()); return Promise.reject(new ApiError("登录已过期,请重新登录", 401)); }
const detail = err.response?.data?.detail;
const msg = typeof detail === "string" ? detail
: Array.isArray(detail) && detail.length ? "提交的数据有误:" + (detail[0]?.msg || "请检查表单")
: err.code === "ECONNABORTED" ? "请求超时,请稍后重试"
: err.message === "Network Error" ? "连不上服务器,确认后端是否在跑"
: "请求失败" + (status ? "(" + status + ")" : "");
return Promise.reject(new ApiError(msg, status));
},
);
/** 跳过 undefined / null / 空串:与旧前端口径一致,避免把空条件发出去改变结果集 */
export function withQuery(path: string, q?: Query): string {
if (!q) return path;
const p = Object.entries(q)
.filter(([, v]) => v !== undefined && v !== null && v !== "")
.map(([k, v]) => encodeURIComponent(k) + "=" + encodeURIComponent(String(v)));
return p.length ? path + "?" + p.join("&") : path;
}
const clean = (q?: Query) => {
if (!q) return undefined;
const o: Query = {};
Object.entries(q).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== "") o[k] = v; });
return o;
};
export const get = async <T>(path: string, q?: Query): Promise<T> => (await http.get<T>(path, { params: clean(q) })).data;
export const post = async <T>(path: string, body?: unknown): Promise<T> => (await http.post<T>(path, body ?? {})).data;
export const patch = async <T>(path: string, body?: unknown): Promise<T> => (await http.patch<T>(path, body ?? {})).data;
export const del = async <T>(path: string, q?: Query): Promise<T> => (await http.delete<T>(path, { params: clean(q) })).data;
/** 导出 Excel:fetch + blob。403/500 的 JSON 错误用 toast 报出,不用 <a> 跳转把 SPA 顶成错误页。
* btn 传触发按钮:等待期间 disabled + aria-busy(等待要有交代)。*/
export async function download(url: string, btn?: (HTMLElement & { disabled?: boolean }) | null, onMsg?: (m: string) => void): Promise<void> {
if (btn) { btn.disabled = true; btn.setAttribute("aria-busy", "true"); }
try {
const res = await fetch("/api" + url, { credentials: "same-origin" });
if (!res.ok) {
let msg = "导出失败(" + res.status + ")";
try { const j = await res.json(); if (j && j.detail) msg = "导出失败:" + String(j.detail); } catch { /* 非 JSON 保留状态码文案 */ }
throw new ApiError(msg, res.status);
}
const blob = await res.blob();
const cd = res.headers.get("content-disposition") || "";
const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(cd);
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = m ? decodeURIComponent(m[1]) : "export.xlsx";
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
onMsg?.("已下载 " + a.download);
} catch (e) {
onMsg?.(apiMsg(e));
throw e;
} finally {
if (btn) { btn.disabled = false; btn.removeAttribute("aria-busy"); }
}
}

View File

@ -0,0 +1,128 @@
/* 接口层:一个端点一个函数;查询参数在离路由最近的地方逐个点名
(tests/test_api_contract.py 会扫本文件:这里的每个键必须在后端 OpenAPI 里声明过,
视图里传上来的未知键会被丢掉,不会悄悄发出去改变结果集)。 */
import { del, get, http, patch, post } from "./client";
import type {
Category, CreatePeriodResult, CustomMeta, CustomProject, EnumItem, Finance, FocusItem, LogRow, Me, Meta, Paged, Periods,
Project, Query, Role, RbacMeta, SessionRow, Settings, Staff, UpdateRow, UserRow, WeeklyData,
} from "../types/domain";
async function put<T>(path: string, body: unknown) { return (await http.put<T>(path, body)).data; }
/* ---------- 会话与权限 ---------- */
export const login = (username: string, password: string) => post<Me>("/auth/login", { username, password });
export const logout = () => post("/auth/logout");
export const fetchMe = () => get<Me>("/auth/me");
export const updateMe = (body: { name?: string }) => put<Me>("/auth/me", body);
export const changePassword = (old_password: string, new_password: string) => post("/auth/password", { old_password, new_password });
/* ---------- 字典 / 周期 / 系统设置 / AI ---------- */
export const fetchMeta = () => get<Meta>("/meta");
export const fetchPeriods = () => get<Periods>("/periods");
/** 新建周期:只给短标签(如「9月第1周」),年份由后端自动接续;返回 { created, period } */
export const createPeriod = (label: string) => post<CreatePeriodResult>("/periods", { label });
/** /health 挂在应用根路径而不是 /api 下(app/main.py),按旧版口径直接取 */
export async function fetchHealth(): Promise<{ ok?: boolean; db?: string; dev?: boolean; boot?: string }> {
const res = await fetch("/health");
if (!res.ok) throw new Error("服务健康检查失败(" + res.status + ")");
return await res.json();
}
export const deletePeriod = (pid: number) => del("/periods/" + pid);
export const fetchSettings = () => get<Settings>("/settings");
/** AI 整理配置:后端收 { values: { ai_api_base, ai_api_key, ai_model, ai_temperature } },空值不覆盖 */
export const saveSettings = (q?: Query) => put<Settings>("/settings", {
values: {
ai_api_base: q?.ai_api_base, ai_api_key: q?.ai_api_key,
ai_model: q?.ai_model, ai_temperature: q?.ai_temperature,
},
});
export const parseAi = (q?: Query) => post<{ parsed: Record<string, any>; model?: string }>("/ai/parse", q);
export const commitAi = (q?: Query) => post("/ai/commit", q);
/* ---------- 自研产品与执行记录 ---------- */
export const fetchProjects = (q?: Query) =>
get<Project[]>("/projects", { category_id: q?.category_id, is_key: q?.is_key, archived: q?.archived, keyword: q?.keyword, owner: q?.owner, period_id: q?.period_id, year: q?.year, month: q?.month });
export const createProject = (body: Query) => post<Project>("/projects", body);
export const fetchProject = (pid: number) => get<{ project: Project; updates?: UpdateRow[]; timeline?: any[] }>("/projects/" + pid);
export const patchProject = (pid: number, body: Query) => patch<Project>("/projects/" + pid, body);
export const deleteProject = (pid: number) => del("/projects/" + pid);
export const fetchCategories = () => get<Category[]>("/categories");
export const createCategory = (body: Query) => post<Category>("/categories", body);
export const patchCategory = (cid: number, body: Query) => patch<Category>("/categories/" + cid, body);
export const deleteCategory = (cid: number) => del("/categories/" + cid);
export const fetchUpdates = (q?: Query) =>
get<UpdateRow[]>("/updates", { project_id: q?.project_id, period_id: q?.period_id, year: q?.year, month: q?.month, limit: q?.limit });
export const createUpdate = (body: Query) => post<UpdateRow>("/updates", body);
export const patchUpdate = (uid: number, body: Query) => patch<UpdateRow>("/updates/" + uid, body);
export const deleteUpdate = (uid: number) => del("/updates/" + uid);
export const fetchWeekly = (q?: Query) =>
get<WeeklyData>("/weekly", { period_id: q?.period_id, year: q?.year, month: q?.month, owner: q?.owner, all_custom: q?.all_custom });
/* ---------- 每周重点工作 ---------- */
export const fetchFocus = (q?: Query) => get<FocusItem[]>("/focus", { archived: q?.archived, status: q?.status, keyword: q?.keyword });
export const createFocus = (body: Query) => post<FocusItem>("/focus", body);
export const patchFocus = (fid: number, body: Query) => patch<FocusItem>("/focus/" + fid, body);
export const deleteFocus = (fid: number) => del("/focus/" + fid);
/* ---------- 定制项目 ---------- */
export const fetchCustomMeta = () => get<CustomMeta>("/custom/meta");
export const fetchCustoms = (q?: Query) =>
get<CustomProject[]>("/custom/projects", { stage: q?.stage, region: q?.region, keyword: q?.keyword, archived: q?.archived, owner: q?.owner });
export const createCustom = (body: Query) => post<CustomProject>("/custom/projects", body);
export const fetchCustom = (cid: number) => get<{ project: CustomProject; updates?: any[]; pipeline?: EnumItem[] }>("/custom/projects/" + cid);
export const patchCustom = (cid: number, body: Query) => patch<CustomProject>("/custom/projects/" + cid, body);
export const deleteCustom = (cid: number) => del("/custom/projects/" + cid);
export const fetchCustomFinance = (q?: Query) =>
get<Finance>("/custom/finance", { period_id: q?.period_id, year: q?.year, month: q?.month });
export const createCustomUpdate = (body: Query) => post("/custom/updates", body);
export const patchCustomUpdate = (uid: number, body: Query) => patch("/custom/updates/" + uid, body);
export const deleteCustomUpdate = (uid: number) => del("/custom/updates/" + uid);
export const parseCustomAi = (q?: Query) => post<{ parsed: Record<string, any> }>("/custom/ai/parse", q);
export const commitCustomAi = (q?: Query) => post("/custom/ai/commit", q);
export const fetchAnnualTargets = (q?: Query) => get<Record<string, any>>("/custom/annual-targets", { year: q?.year });
export const saveAnnualTargets = (year: number, targets: Record<string, number>) => put<Record<string, any>>("/custom/annual-targets", { year, targets });
/* ---------- 人力资源 ---------- */
export const fetchStaff = (q?: Query) =>
get<{ items: Staff[]; summary?: Record<string, any>; dict?: { groups: string[]; affiliations: string[] } }>("/staff",
{ archived: q?.archived, group: q?.group, keyword: q?.keyword });
export const createStaff = (body: Query) => post<Staff>("/staff", body);
export const patchStaff = (sid: number, body: Query) => patch<Staff>("/staff/" + sid, body);
export const deleteStaff = (sid: number, force?: boolean) => del("/staff/" + sid, force ? { force: true } : undefined);
/* ---------- 权限管理 ---------- */
export const fetchRbacMeta = () => get<RbacMeta>("/rbac/meta");
export const fetchRoles = () => get<Role[]>("/rbac/roles");
export const createRole = (body: Query) => post<Role>("/rbac/roles", body);
export const patchRole = (rid: number, body: Query) => patch<Role>("/rbac/roles/" + rid, body);
export const deleteRole = (rid: number) => del("/rbac/roles/" + rid);
export const fetchUsers = () => get<UserRow[]>("/rbac/users");
export const createUser = (body: Query) => post<UserRow>("/rbac/users", body);
export const patchUser = (uid: number, body: Query) => patch<UserRow>("/rbac/users/" + uid, body);
export const deleteUser = (uid: number) => del("/rbac/users/" + uid);
export const revokeUser = (uid: number) => post("/rbac/users/" + uid + "/revoke");
export const fetchSessions = () => get<SessionRow[]>("/rbac/sessions");
export const revokeSession = (token: string) => del("/rbac/sessions/" + encodeURIComponent(token));
export const fetchLogs = (q?: Query) =>
get<Paged<LogRow>>("/rbac/logs", { username: q?.username, menu: q?.menu, action: q?.action, days: q?.days, limit: q?.limit, offset: q?.offset });
export const clearLogs = (days: number) => del("/rbac/logs", { days });
/* ---------- 导出 Excel(返回完整 URL,交给 download() 走 fetch+blob)---------- */
export const exportProjectsUrl = (q?: Query) =>
"/export/projects" + tail({ category_id: q?.category_id, keyword: q?.keyword, owner: q?.owner, idle_only: q?.idle_only, period_id: q?.period_id, year: q?.year, month: q?.month, archived: q?.archived });
export const exportUpdatesUrl = (q?: Query) =>
"/export/updates" + tail({ period_id: q?.period_id, year: q?.year, month: q?.month, project_id: q?.project_id, keyword: q?.keyword });
export const exportFocusUrl = (q?: Query) =>
"/export/focus" + tail({ archived: q?.archived, status: q?.status, keyword: q?.keyword });
export const exportCustomUrl = (q?: Query) =>
"/export/custom" + tail({ region: q?.region, origin: q?.origin, status: q?.status, risk: q?.risk, accept_plan: q?.accept_plan, keyword: q?.keyword, archived: q?.archived });
export const exportCustomUpdatesUrl = (q?: Query) =>
"/export/custom-updates" + tail({ period_id: q?.period_id, year: q?.year, month: q?.month, keyword: q?.keyword });
export const exportStaffUrl = (q?: Query) =>
"/export/staff" + tail({ archived: q?.archived, group: q?.group, keyword: q?.keyword });
function tail(q: Query): string {
const p = Object.entries(q).filter(([, v]) => v !== undefined && v !== null && v !== "")
.map(([k, v]) => encodeURIComponent(k) + "=" + encodeURIComponent(String(v)));
return p.length ? "?" + p.join("&") : "";
}

View File

@ -0,0 +1,34 @@
import { Alert, Skeleton } from "antd";
import { Icon, iconForEmpty } from "../icons/Icon";
/** 加载占位:骨架屏比「加载中…」更能交代结构,也避免布局跳动 */
export const TableSkeleton = ({ rows = 6 }: { rows?: number }) => <div className="pad"><Skeleton active paragraph={{ rows }} title={false} /></div>;
export const CardSkeleton = ({ rows = 4 }: { rows?: number }) => <div className="pad"><Skeleton active paragraph={{ rows }} /></div>;
/** 空态:图标 + 文案(文案里带「没有 / 暂无 / 找不到」等关键词时自动换图标)*/
export function EmptyState({ text = "没有数据", hint }: { text?: string; hint?: string }) {
return (
<div className="empty">
<Icon name={iconForEmpty(text)} className="ic-lg" />
<div>{text}</div>
{hint ? <div className="empty-hint">{hint}</div> : null}
</div>
);
}
/** 失败态:可重试;role=alert 由 AntD Alert 自带 */
export function ErrorState({ text, onRetry }: { text: string; onRetry?: () => void }) {
return (
<div className="pad">
<Alert type="error" showIcon title={"加载失败:" + text} action={onRetry ? <button className="link-antd" onClick={onRetry}>重试</button> : undefined} />
</div>
);
}
/** 提示条(非阻断说明):info / warn / err 三档 */
export function Notice({ kind = "info", children }: { kind?: "info" | "warn" | "err"; children: React.ReactNode }) {
return (
<div className={"notice " + kind} role={kind === "err" ? "alert" : undefined}>
<Icon name={kind === "info" ? "info" : "alert-circle"} className="ti" />
<div>{children}</div>
</div>
);
}

View File

@ -0,0 +1,45 @@
import { Button, Drawer } from "antd";
import type { ReactNode } from "react";
/**
* 新增 / 修改表单的统一容器:一律右侧侧滑(用户要求:表单不混用弹窗)。
* 破坏性动作的确认框不在这里,仍走 modal.confirm(危险按钮 danger)。
* 头部结构与其他抽屉同款(.drawer-head-text / .dlg-title / .drawer-sub),底部固定「取消 + 保存」右对齐,
* 焦点进出、Esc 关闭、焦点归还触发元素都交给 AntD Drawer,不自己实现焦点栈。
*/
export function FormDrawer(props: {
open: boolean;
title: ReactNode;
subtitle?: ReactNode;
onClose: () => void;
onSubmit: () => void;
okText?: string;
cancelText?: string;
busy?: boolean;
width?: number;
children: ReactNode;
/** 追加到抽屉根节点的类名(各视图的局部尺寸规则挂在它下面)*/
className?: string;
/** 需要自定义底部(比如右侧再放个说明)时给;给了就不再渲染默认按钮 */
footer?: ReactNode;
}) {
const { open, title, subtitle, onClose, onSubmit, okText = "保存", cancelText = "取消", busy, width = 560, children, footer, className } = props;
return (
<Drawer className={"form-drawer" + (className ? " " + className : "")} open={open} placement="right" width={width} onClose={onClose} destroyOnHidden
keyboard={!busy}
title={<div className="drawer-head-text">
<h2 className="dlg-title">{title}</h2>
{subtitle ? <div className="drawer-sub">{subtitle}</div> : null}
</div>}>
<div className="drawer-body">{children}</div>
{footer === undefined ? (
<div className="btn-bar">
<Button onClick={onClose} disabled={busy}>{cancelText}</Button>
{/* 表单校验失败会让 onSubmit 的 promise reject(AntD Form 的老行为),这里吞掉即可:
错误已经在字段下面红字显示,不要再往控制台丢一条 unhandled rejection */}
<Button type="primary" loading={busy} onClick={() => { void Promise.resolve(onSubmit()).catch(() => undefined); }}>{okText}</Button>
</div>
) : footer}
</Drawer>
);
}

View File

@ -0,0 +1,45 @@
import { Input } from "antd";
import type { InputRef } from "antd";
import { useEffect, useRef, useState } from "react";
import { useUi } from "../store/ui";
import { useDebounced } from "../utils/hooks";
/**
* 卡头搜索框:与顶栏全局搜索完全同款(320ms 防抖、共用 useUi.keyword)。
* 旧版 focus/projects/custom/staff 四处页内搜索走的就是这条通道(bindKeyword),
* 两处输入必须互相同步:本框在被别处(顶栏或另一个框)改动且自己没被聚焦时回灌,
* 否则会出现「一边打字一边把另一边打回」的抢输入问题。
*/
export function KeywordBox({ placeholder, width = 180 }: { placeholder: string; width?: number }) {
const keyword = useUi((s) => s.keyword);
const setKeyword = useUi((s) => s.set);
const [value, setValue] = useState(keyword);
const ref = useRef<InputRef>(null);
const debounced = useDebounced(value);
useEffect(() => { // 别处改了关键字:只要自己没在编辑就跟上
const el = ref.current?.input;
if (el && document.activeElement === el) return;
setValue(keyword);
}, [keyword]);
useEffect(() => { // 320ms 防抖后写回全局状态
const next = debounced.trim();
if (next !== keyword) setKeyword({ keyword: next });
}, [debounced, keyword, setKeyword]);
return (
<Input
ref={ref}
className="search"
size="small"
type="search"
allowClear
style={{ width }}
placeholder={placeholder}
aria-label={placeholder}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}

View File

@ -0,0 +1,20 @@
import { Icon, IconBadge } from "../icons/Icon";
/** KPI 卡:图标 + 标签 + 大数字 + 脚注。重点色只出现在图标与数字上(--c 注入)。
* 标签与脚注会被挤窄,一律单行截断 + title 兜全文;数字用等宽数字防跳动。*/
export function KpiCard({ icon, label, value, foot, accent, size = "lg" }: {
icon: string; label: string; value: React.ReactNode; foot?: React.ReactNode; accent?: string; size?: "lg" | "sm" | "xs";
}) {
return (
<div className={"kpi" + (accent ? " accent-" + accent : "")}>
<IconBadge name={icon} />
<div className="k-label" title={label}>{label}</div>
<div className={"k-value" + (size === "sm" ? " sm" : size === "xs" ? " xs" : "")}>{value}</div>
{foot ? <div className="k-foot" title={typeof foot === "string" ? foot : undefined}>{foot}</div> : null}
</div>
);
}
export const KpiGrid = ({ cols = 5, children }: { cols?: number; children: React.ReactNode }) => (
<div className="grid kpi" style={{ "--cols": String(cols) } as React.CSSProperties}>{children}</div>
);
export const KpiIcon = Icon;

View File

@ -0,0 +1,46 @@
import { Alert, Button, Form, Input, type InputRef } from "antd";
import { useEffect, useRef, useState } from "react";
import { apiMsg } from "../api/client";
import { useSession } from "../store/session";
import { Icon } from "../icons/Icon";
/** 登录门:未登录或会话过期时盖住整页(不跳路由,保住已填表单)。回车提交、错误 role=alert。*/
export function LoginGate() {
const signIn = useSession((s) => s.signIn);
const [err, setErr] = useState("");
const [busy, setBusy] = useState(false);
const [form] = Form.useForm();
const userRef = useRef<InputRef>(null);
useEffect(() => { userRef.current?.focus(); }, []);
const submit = async () => {
const v = await form.validateFields();
setBusy(true); setErr("");
try { await signIn(v.username, v.password); }
catch (e) { setErr(apiMsg(e)); userRef.current?.focus(); }
finally { setBusy(false); }
};
return (
<div className="auth-shell" role="dialog" aria-modal="true" aria-labelledby="authTitle">
<div className="auth-box">
<div className="auth-brand">
<div className="brand-mark lg"><Icon name="target" /></div>
<h1>DMS管理平台</h1>
<p>软件开发部 · 关键任务与项目跟踪。登录后按角色看到有权限的菜单。</p>
</div>
<div className="auth-form">
<h2 id="authTitle">登录</h2>
<Form form={form} layout="vertical" requiredMark={false} onFinish={submit}>
<Form.Item label="账号" name="username" rules={[{ required: true, message: "请填写账号" }]}>
<Input ref={userRef} autoComplete="username" placeholder="admin" />
</Form.Item>
<Form.Item label="密码" name="password" rules={[{ required: true, message: "请填写密码" }]}>
<Input.Password autoComplete="current-password" placeholder="••••••" />
</Form.Item>
{err ? <Alert type="error" showIcon message={err} className="auth-err" /> : null}
<Button type="primary" htmlType="submit" block loading={busy} className="auth-ok">登录</Button>
</Form>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,53 @@
import { Alert, App, Input } from "antd";
import { FormDrawer } from "./FormDrawer";
import { useEffect, useState } from "react";
import { apiMsg } from "../api/client";
import * as api from "../api/endpoints";
import { useMeta } from "../store/meta";
import { useUi } from "../store/ui";
/**
* 新建周期(旧版 createNewPeriod):只填「9月第1周」这种短标签,年份由后端自动接续;新增表单 → 侧滑面板。
* 已存在时后端回 created=false 但仍给出周期,前端照样切过去。
* 设置页「新增」与顶栏周期下拉的「+ 新建周期…」共用这一个。
*/
export function NewPeriodModal({ open, onClose, onCreated }: { open: boolean; onClose: () => void; onCreated?: (id: number | null) => void }) {
const { message } = App.useApp();
const [label, setLabel] = useState("");
const [err, setErr] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => { if (open) { setLabel(""); setErr(""); setBusy(false); } }, [open]);
const submit = async () => {
const l = label.trim();
if (!l) { setErr("请填写周期名称"); return; } // 旧版弹层内原文案
setErr("");
setBusy(true); // 提交即禁用,失败恢复
try {
const r = await api.createPeriod(l);
const pid = r.period ? r.period.id : null;
await useMeta.getState().refreshPeriods();
if (pid !== null) useUi.getState().set({ gran: "week", weekId: pid }); // 顶栏跟着切到这一周
message.success(r.created
? "已新增周期 " + ((r.period && (r.period.full_label || r.period.label)) || "")
: "周期 " + ((r.period && (r.period.full_label || r.period.label)) || "") + " 已存在,已切换");
onCreated?.(pid);
onClose();
} catch (e) {
setBusy(false);
setErr(apiMsg(e)); // 弹层里的错误只出现在弹层里
}
};
return (
<FormDrawer open={open} title="新建周期" subtitle="只填短标签,年份与周次由后端按现有周期接续"
onClose={onClose} onSubmit={submit} okText="创建" busy={busy} width={460}>
<div className="form-row">
<label htmlFor="newPeriodLabel">周期名称</label>
<Input id="newPeriodLabel" autoFocus value={label} placeholder="如:9月第1周"
onChange={(e) => setLabel(e.target.value)} onPressEnter={submit} />
</div>
{err ? <Alert type="error" showIcon title={err} /> : null}
</FormDrawer>
);
}

View File

@ -0,0 +1,22 @@
/** 页面抬头:h2 标题 + 一句话说明,八个视图同一个结构(NEX 08.1)*/
export function PageHead({ title, desc, actions }: { title: string; desc?: string; actions?: React.ReactNode }) {
return (
<div className="page-head">
<div>
<h2 className="page-title">{title}</h2>
{desc && <p className="page-desc">{desc}</p>}
</div>
{actions ? <div className="page-actions">{actions}</div> : null}
</div>
);
}
export const VIEW_META: Record<string, [string, string]> = {
board: ["工作看板", "本期重点项目、每周工作、执行记录与验收风险"],
projects: ["自研产品", "在研项目的执行记录、进度与状态"],
custom: ["定制项目", "定制与定开项目的台账、本周进展、年度任务"],
focus: ["每周工作", "每周重点工作的登记、延期与归档"],
staff: ["人力资源", "全系统负责人的唯一来源"],
intake: ["更新录入", "批量录入执行记录或交付记录,可直接写入或 AI 整理"],
settings: ["设置", "系统配置、周期管理与数据库信息"],
rbac: ["权限管理", "角色、用户、在线会话与操作日志"],
};

View File

@ -0,0 +1,35 @@
import { Pagination } from "antd";
import { useRef } from "react";
import { PAGE_SIZES, useUi } from "../store/ui";
/** 全站统一分页条:一页装得下就不显示;贴列表右下角(样式见 app.css .pager)。
* 交互对齐成熟台账产品:共 N 条 + 当前区间、每页条数(10/20/50/100,全站共用,默认 10)、
* 页码 / 前后页 / 快速跳页;翻页或换每页条数后滚回表头,不再停在列表底部。 */
export function PagerBar({ total, current, onChange, onSizeChange, label }: {
total: number; current: number; onChange: (p: number) => void; onSizeChange?: (n: number) => void; label: string;
}) {
const pageSize = useUi((s) => s.pageSize);
const ref = useRef<HTMLElement | null>(null);
if (Math.ceil(total / pageSize) < 2) return null;
/* 翻页后把同一张卡的表格顶部滚回视野(.ant-table-wrapper 上配了 scroll-margin 避开吸顶栏)*/
const backToTop = () => {
const card = ref.current?.closest(".card");
const tbl = card?.querySelector(".ant-table-wrapper") || card?.querySelector("table");
tbl?.scrollIntoView({ behavior: "smooth", block: "start" });
};
return (
<nav ref={ref} className="pager" aria-label={label + "分页导航"}>
<Pagination
size="small"
current={current}
total={total}
pageSize={pageSize}
showSizeChanger={!!onSizeChange}
pageSizeOptions={PAGE_SIZES.map(String)}
showQuickJumper
showTotal={(t, [from, to]) => (to > from ? `共 ${t} 条 · 显示 ${from}\u2013${to}` : `共 ${t} 条`)}
onChange={(p, size) => { if (size !== pageSize) onSizeChange?.(size); else onChange(p); backToTop(); }}
/>
</nav>
);
}

View File

@ -0,0 +1,33 @@
import { Card } from "antd";
import type { ReactNode } from "react";
import { Icon, iconForTitle } from "../icons/Icon";
/** 卡 = AntD Card + 真标题(h3,卡片内允许再开 h4)。标题前导图标按关键词自动补,
* 与旧版 icons.js 的 auto() 同一套规则,只是改成渲染期计算,不再用 MutationObserver。*/
export function PanelCard({ title, count, tools, children, extraClass, foot, id }: {
title?: ReactNode; count?: number | string; tools?: ReactNode; children: ReactNode; extraClass?: string; foot?: ReactNode; id?: string;
}) {
const plain = typeof title === "string" ? title : "";
const autoIcon = plain ? iconForTitle(plain) : "";
const head = title === undefined ? undefined : (
<div className="card-head">
<h3 id={id}>{autoIcon ? <Icon name={autoIcon} className="ti" /> : null}{title}
{count !== undefined && <span className="cnt">{count}</span>}
</h3>
{tools ? <div className="card-tools">{tools}</div> : null}
</div>
);
return (
<Card className={"card" + (extraClass ? " " + extraClass : "")} variant="borderless" styles={{ body: { padding: 0 } }} title={head} extra={undefined}>
{children}
{foot ? <div className="card-foot">{foot}</div> : null}
</Card>
);
}
/** 区块标题(卡内分段):h4 + 一条延伸细线 */
export function SectionTitle({ children }: { children: ReactNode }) {
const plain = typeof children === "string" ? children : "";
const icon = plain ? iconForTitle(plain) : "";
return <h4 className="sec-title">{icon ? <Icon name={icon} className="ti" /> : null}{children}</h4>;
}

View File

@ -0,0 +1,79 @@
import { Button, Segmented, Select } from "antd";
import { useEffect, useMemo, useState } from "react";
import { useMeta } from "../store/meta";
import { useUi } from "../store/ui";
import type { Gran } from "../types/domain";
import { Icon } from "../icons/Icon";
import { NewPeriodModal } from "./NewPeriodModal";
import { periodCrossNote, periodOptionLabel, periodRangeText, type PeriodRow } from "../utils/period";
import { useCan } from "../store/session";
/** 周期条:周/月粒度 + 前后翻期 + 周期下拉 + 新建周期。全站唯一的周期口径出口
* (周取 periods.weeks 的 period_id,月取 year+month 合成,与旧版 scopeQuery/finQuery 一致)。
* 下拉里每个周期直接带上起止日期,跨月周的口径写在旁边的小字里(旧版 renderPeriodSelect)。*/
export function PeriodPicker() {
const periods = useMeta((s) => s.periods);
const { gran, weekId, monthIdx, set } = useUi();
const { w } = useCan();
const [newOpen, setNewOpen] = useState(false);
const weeks = (periods?.weeks || []) as PeriodRow[];
const months = periods?.months || [];
/* 首次进入或切粒度时补齐选中项:默认落在「本期」(periods.today_id 指向的那一周)*/
useEffect(() => {
if (!periods) return;
if (gran === "week" && !weeks.some((x) => x.id === weekId)) set({ weekId: periods.today_id ?? weeks[0]?.id ?? null });
if (gran === "month" && (monthIdx === null || !months[monthIdx])) {
const hit = months.findIndex((m) => (m.period_ids || []).includes(periods.today_id ?? -1));
set({ monthIdx: hit >= 0 ? hit : Math.max(0, months.length - 1) });
}
}, [periods, gran, weekId, monthIdx, weeks, months, set]);
const NEW = -1; // 下拉里的「+ 新建周期…」虚拟项
const options = useMemo(() => {
if (gran === "week") {
const opts = weeks.map((wk, i) => ({ value: i, label: periodOptionLabel(wk) }));
if (w("settings")) opts.push({ value: NEW, label: "+ 新建周期…" });
return opts;
}
return months.map((m, i) => {
const r = periodRangeText(m as PeriodRow);
const n = m.week_count || (m.period_ids || []).length;
return { value: i, label: m.label + "(" + (r || "—") + " · " + n + " 周)" };
});
}, [gran, weeks, months, w]);
const index = gran === "week" ? Math.max(0, weeks.findIndex((x) => x.id === weekId)) : (monthIdx ?? 0);
const step = (delta: number) => {
const next = Math.min(Math.max(index + delta, 0), Math.max(weeks.length || months.length - 1, 0));
if (gran === "week") set({ weekId: weeks[next]?.id ?? null }); else set({ monthIdx: next });
};
const pick = (i: number) => {
if (i === NEW) { setNewOpen(true); return; } // 选了虚拟项:只开弹窗,不改当前周期
if (gran === "week") set({ weekId: weeks[i]?.id ?? null }); else set({ monthIdx: i });
};
// 口径写在顶栏:周 = 自然周(跨月整周算进周四那个月),月 = 该月各自然周的并集(不等于自然月)
const hint = useMemo(() => {
if (gran === "week") return periodCrossNote(weeks.find((x) => x.id === weekId));
const r = periodRangeText((months[monthIdx ?? 0] || {}) as PeriodRow);
return r ? "月口径 = 该月各自然周的并集 " + r + ",不等于自然月 1 号~月末" : "月视图 · 自动汇总该月所有周";
}, [gran, weeks, months, weekId, monthIdx]);
return (
<div className="period-bar">
<Segmented
aria-label="统计粒度"
size="small"
value={gran}
options={[{ value: "week", label: "周" }, { value: "month", label: "月" }]}
onChange={(v) => set({ gran: v as Gran })}
/>
<Button className="nav-arrow" type="text" aria-label="上一期" title="上一期" disabled={index <= 0} icon={<Icon name="chevron-left" />} onClick={() => step(-1)} />
<Select className="period-select" aria-label="选择周期" value={index} options={options} onChange={pick} popupMatchSelectWidth={false} />
<Button className="nav-arrow" type="text" aria-label="下一期" title="下一期" disabled={gran === "week" ? index >= weeks.length - 1 : index >= months.length - 1} icon={<Icon name="chevron-right" />} onClick={() => step(1)} />
<span className="period-hint">{hint}</span>
<NewPeriodModal open={newOpen} onClose={() => setNewOpen(false)} />
</div>
);
}

View File

@ -0,0 +1,43 @@
import { App, Form, Input } from "antd";
import { useEffect, useState } from "react";
import { apiMsg } from "../api/client";
import * as api from "../api/endpoints";
import { useSession } from "../store/session";
import { FormDrawer } from "./FormDrawer";
/** 个人设置:只允许改自己的姓名与密码(角色由权限管理页管)。改的是自己的资料,属于修改表单 → 侧滑面板 */
export function ProfileModal({ open, onClose }: { open: boolean; onClose: () => void }) {
const me = useSession((s) => s.me);
const setMe = useSession((s) => s.setMe);
const { message } = App.useApp();
const [form] = Form.useForm();
const [busy, setBusy] = useState(false);
useEffect(() => { if (open) form.setFieldsValue({ name: me?.name || "", old: "", next: "" }); }, [open, me, form]);
const submit = async () => {
const v = await form.validateFields();
setBusy(true);
try {
const body: Record<string, unknown> = { name: v.name };
if (v.next) body.new_password = v.next;
if (v.next && !v.old) { message.warning("修改密码要先填当前密码"); setBusy(false); return; }
const updated = await api.updateMe({ name: v.name });
if (v.next) await api.changePassword(v.old, v.next);
setMe(updated);
message.success("已保存");
onClose();
} catch (e) { message.error(apiMsg(e)); }
finally { setBusy(false); }
};
return (
<FormDrawer open={open} title="个人设置" onClose={onClose} onSubmit={submit} okText="保存" busy={busy}>
<p className="dlg-hint">账号 <b>{me?.username}</b> · 角色 {(me?.role_names || []).join(" / ") || "未分配"}</p>
<Form form={form} layout="vertical" requiredMark={false}>
<Form.Item label="姓名" name="name"><Input placeholder="显示在界面右上角的名字" /></Form.Item>
<Form.Item label="当前密码" name="old" extra="只有要改密码时才填"><Input.Password autoComplete="current-password" /></Form.Item>
<Form.Item label="新密码" name="next" rules={[{ validator: async (_r, v) => { if (v && v.length < 6) throw new Error("新密码至少 6 位"); } }]}>
<Input.Password autoComplete="new-password" />
</Form.Item>
</Form>
</FormDrawer>
);
}

View File

@ -0,0 +1,91 @@
import { useCallback, useMemo, useState } from "react";
import type { TableProps } from "antd";
/** 拖拽调列宽(参考成熟台账:表头右缘把手,拖动即调、双击恢复默认、方向键微调)。
* 宽度按表存 localStorage(unis.colw.v1.<key>),刷新 / 重开保留;不引入第三方依赖。
* 用法:const rz = useResizableColumns(key, cols) → <Table columns={rz.columns} components={rz.components}
* tableLayout="fixed" scroll={{ x: rz.totalWidth }} />。列必须有 key,width 作为基准宽度。 */
const LS = "unis.colw.v1.";
export const RZ_MIN = 60;
export const RZ_MAX = 720;
function load(key: string): Record<string, number> {
try { const o = JSON.parse(localStorage.getItem(LS + key) || "{}"); return o && typeof o === "object" ? o : {}; } catch { return {}; }
}
function persist(key: string, w: Record<string, number>) {
try { localStorage.setItem(LS + key, JSON.stringify(w)); } catch { /* 隐私模式存不下就算了:只丢记忆,不丢功能 */ }
}
type CellProps = React.ThHTMLAttributes<HTMLTableCellElement> & { "data-rzkey"?: string; "data-rzw"?: string };
/* 把手通过 context 外唯一办法拿不到函数:直接闭包生成单元格组件(data-* 传字符串,不污染 DOM 属性)*/
function makeHeaderCell(resize: (k: string, w: number) => void, reset: (k: string) => void) {
return function ResizableTitle(props: CellProps) {
const { "data-rzkey": rzKey, "data-rzw": rzw, children, ...rest } = props;
if (!rzKey) return <th {...rest}>{children}</th>;
return (
<th {...rest} onClickCapture={(e) => {
/* 拖动结束会补发一次 click:若是拖过而不是点过,吞掉它,别误触发表头排序 */
const el = e.currentTarget as HTMLElement;
if (el.dataset.rzMoved) { delete el.dataset.rzMoved; e.stopPropagation(); e.preventDefault(); }
}}>
{children}
<span className="th-rz" role="separator" aria-orientation="vertical" tabIndex={0}
title="拖动调整列宽 · 双击恢复默认 · ←/→ 微调"
onPointerDown={(e) => {
const handle = e.currentTarget as HTMLElement;
const th = handle.parentElement as HTMLElement;
e.preventDefault(); e.stopPropagation();
const sx = e.clientX;
const w0 = Math.max(RZ_MIN, Number(rzw) || Math.round(th.getBoundingClientRect().width) || 140);
let last = w0; let moved = false;
document.body.classList.add("rz-ing");
const move = (ev: PointerEvent) => {
const w = Math.min(RZ_MAX, Math.max(RZ_MIN, Math.round(w0 + ev.clientX - sx)));
if (Math.abs(ev.clientX - sx) > 2) moved = true;
if (w !== last) { last = w; resize(rzKey, w); }
};
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
document.body.classList.remove("rz-ing");
if (moved && th) th.dataset.rzMoved = "1";
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
}}
onDoubleClick={(e) => { e.preventDefault(); e.stopPropagation(); reset(rzKey); }}
onKeyDown={(e) => {
const cur = Math.max(RZ_MIN, Number(rzw) || 140);
if (e.key === "ArrowLeft") { e.preventDefault(); resize(rzKey, Math.max(RZ_MIN, cur - 10)); }
else if (e.key === "ArrowRight") { e.preventDefault(); resize(rzKey, Math.min(RZ_MAX, cur + 10)); }
else if (e.key === "Home") { e.preventDefault(); reset(rzKey); }
}} />
</th>
);
};
}
export function useResizableColumns<T>(tableKey: string, cols: NonNullable<TableProps<T>["columns"]>) {
const [widths, setWidths] = useState<Record<string, number>>(() => load(tableKey));
const resize = useCallback((k: string, w: number) => {
setWidths((prev) => { const next = { ...prev, [k]: w }; persist(tableKey, next); return next; });
}, [tableKey]);
const reset = useCallback((k: string) => {
setWidths((prev) => { const next = { ...prev }; delete next[k]; persist(tableKey, next); return next; });
}, [tableKey]);
const components = useMemo(() => ({ header: { cell: makeHeaderCell(resize, reset) } }), [resize, reset]);
const columns = useMemo(() => {
const mapped = (cols || []).map((c, i) => {
const col = c as Record<string, unknown>;
const ck = String(col.key ?? col.dataIndex ?? "c" + i);
const own = typeof col.onHeaderCell === "function" ? (col.onHeaderCell as (x: unknown) => object) : undefined;
const w = widths[ck] ?? (typeof col.width === "number" ? col.width : 140);
return { ...c, width: w, onHeaderCell: (head: unknown) => ({ ...(own ? own(head) || {} : {}), "data-rzkey": ck, "data-rzw": String(w) }) };
});
return mapped as NonNullable<TableProps<T>["columns"]>;
}, [cols, widths]);
const totalWidth = useMemo(() => (columns as unknown as { width?: number }[]).reduce((a, c) => a + (Number(c.width) || 140), 0), [columns]);
return { columns, components, totalWidth };
}

View File

@ -0,0 +1,205 @@
import { useEffect, useRef, useState } from "react";
import { Popover } from "antd";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { Bold } from "@tiptap/extension-bold";
import { Italic } from "@tiptap/extension-italic";
import { mergeAttributes } from "@tiptap/core";
import { TextStyle } from "@tiptap/extension-text-style";
import { Icon } from "../icons/Icon";
import type { Editor } from "@tiptap/core";
import { RICH_COLORS, sanitizeRich, textToHtml } from "../utils/richtext";
/**
* 正文富文本:加粗 / 斜体 / 下划线 / 语义色 / 清除格式。内核用 Tiptap(ProseMirror),
* 回车分块、选区、中文输入法、撤销栈都交给它——这几件事手写 contentEditable 反复出问题。
*
* 关键约束:工具栏是 headless 的,长得还是项目里那套 NEX 图标按钮 + 色块面板;
* 颜色存**语义名**(<span data-c="danger">)而不是 hex,所以 utils/richtext 的存储约定、
* RichText 展示端、app/export.py 的 Excel 降级、搜索都不用跟着改。
*/
/* 加粗 / 斜体默认产出 <strong>/<em>,我们的存储约定和展示端白名单只认 <b>/<i>;
解析仍然两种都收(默认 parseHTML 不变),只有产出的时候统一成短标签。 */
const BoldB = Bold.extend({ renderHTML: ({ HTMLAttributes }) => ["b", mergeAttributes(HTMLAttributes), 0] });
const ItalicI = Italic.extend({ renderHTML: ({ HTMLAttributes }) => ["i", mergeAttributes(HTMLAttributes), 0] });
const TOOLS = [
{ name: "bold", icon: "bold", label: "加粗", tip: "加粗(Ctrl+B)" },
{ name: "italic", icon: "italic", label: "斜体", tip: "斜体(Ctrl+I)" },
{ name: "underline", icon: "underline", label: "下划线", tip: "下划线(Ctrl+U)" },
] as const;
/* 语义色挂到 TextStyle 上:解析认 data-c(旧数据里没有 style),产出也只写 data-c
—— 官方 Color 扩展存的是 hex,那会让颜色脱离主题 token */
const SemanticColor = TextStyle.extend({
parseHTML() {
return [{
tag: "span",
consuming: false,
getAttrs: (el: HTMLElement) => (el.hasAttribute("data-c") || el.hasAttribute("style") ? {} : false),
}];
},
addAttributes() {
return {
code: {
default: null,
parseHTML: (el: HTMLElement) => el.getAttribute("data-c"),
renderHTML: (attrs: { code?: string | null }) => (attrs.code ? { "data-c": attrs.code } : {}),
},
};
},
});
/* 单行内容不该被 <p> 包一层:库里旧数据是裸文本 + <br>,保持一致,别一保存就全长出标签 */
function unwrapOnePara(html: string): string {
const t = html.trim();
const m = /^<p>([\s\S]*)<\/p>$/.exec(t);
if (m && !/<\/?p\b/i.test(m[1])) return m[1];
return t;
}
/* 对外抛出的 HTML */
function normalizeOut(html: string): string {
return unwrapOnePara(html)
.replace(/<br class="[^"]*">/g, "<br>")
// 空段落要留一个 <br>,否则存出去就是 <p></p>:编辑时看得见空行,展示时行盒是 0,两边不一致
.replace(/<p><\/p>/g, "<p><br></p>");
}
/* 外部值 → 编辑器输入:裸文本 / 纯文本换行 / Chrome 早年留下的 <div> 全归到 <p> 段落 */
function toEditorHtml(v: string | null | undefined): string {
const s = v == null ? "" : String(v);
if (!s) return "";
const html = /<[a-z]/i.test(s) ? sanitizeRich(s) : textToHtml(s);
return html.replace(/<div\b[^>]*>/gi, "<p>").replace(/<\/div>/gi, "</p>");
}
const syncState = (e: Editor) => ({
bold: e.isActive("bold"),
italic: e.isActive("italic"),
underline: e.isActive("underline"),
color: String(e.getAttributes("textStyle").code || ""),
});
export function RichEditor(props: {
value: string;
onChange: (html: string) => void;
rows?: number;
id?: string;
ariaLabel?: string;
placeholder?: string;
/** 追加到编辑区节点的类名(录入页的大框沿用自己的尺寸类)*/
className?: string;
}) {
const { value, onChange, rows = 5, id, ariaLabel, placeholder, className } = props;
const [panel, setPanel] = useState(false);
const [active, setActive] = useState({ bold: false, italic: false, underline: false, color: "" });
const last = useRef(""); // 上一次对外抛出的 HTML,用来分辨是不是外部回填
const stateRef = useRef(""); // 上一次同步的按钮态,避免每个事务都 setState
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const editor = useEditor({
extensions: [
StarterKit.configure({
bold: false, italic: false,
heading: false, code: false, codeBlock: false, blockquote: false, horizontalRule: false,
bulletList: false, orderedList: false, listItem: false, strike: false, link: false,
}),
BoldB, ItalicI, SemanticColor,
],
content: toEditorHtml(value),
editorProps: {
attributes: {
class: "rich-editor" + (className ? " " + className : ""),
style: "min-height: " + Math.round(rows * 22.7 + 20) + "px",
...(id ? { id } : {}),
...(ariaLabel ? { "aria-label": ariaLabel } : {}),
...(placeholder ? { "data-placeholder": placeholder } : {}),
},
},
onCreate: ({ editor: e }) => {
last.current = normalizeOut(e.getHTML());
e.view.dom.setAttribute("data-empty", e.isEmpty ? "true" : "false");
},
onUpdate: ({ editor: e }) => {
const html = normalizeOut(e.getHTML());
last.current = html;
onChangeRef.current(html);
e.view.dom.setAttribute("data-empty", e.isEmpty ? "true" : "false");
},
onTransaction: ({ editor: e }) => {
const s = syncState(e);
const key = [s.bold, s.italic, s.underline, s.color].join("|");
if (key !== stateRef.current) { stateRef.current = key; setActive(s); }
},
});
/* 外部回填(打开抽屉带旧值、撤销整条记录等):正在打字时不回写,否则光标被拽走 */
useEffect(() => {
if (!editor || editor.isFocused) return;
const html = toEditorHtml(value);
const out = normalizeOut(html);
if (out === last.current) return;
last.current = out;
editor.commands.setContent(html, { emitUpdate: false });
editor.view.dom.setAttribute("data-empty", editor.isEmpty ? "true" : "false");
}, [value, editor]);
const applyColor = (code: string) => {
// focus() 会把 ProseMirror 自己记的选区带回来,点面板里的色块不会把选区弄丢
const chain = editor.chain().focus();
if (code) chain.setMark("textStyle", { code });
else chain.unsetMark("textStyle");
chain.run();
setPanel(false);
};
const clearFormat = () => { editor.chain().focus().unsetAllMarks().run(); };
return (
<div className={"rich-field" + (panel ? " panel-open" : "")}
onKeyDown={(e) => { if (e.key === "Escape" && panel) { e.stopPropagation(); setPanel(false); } }}>
{/* 工具栏不能抢焦点:mousedown 挡掉默认行为,选区才不会塌 */}
<div className="rt-bar" role="toolbar" aria-label="正文格式" onMouseDown={(e) => e.preventDefault()}>
{TOOLS.map((t) => (
<button key={t.name} type="button" className={"rt-btn" + (active[t.name] ? " on" : "")}
aria-pressed={active[t.name]} title={t.tip} aria-label={t.label}
onClick={() => editor.chain().focus().toggleMark(t.name).run()}>
<Icon name={t.icon} size={15} />
</button>
))}
<span className="rt-sep" aria-hidden="true" />
{/* 面板不能抢焦点,否则点色块的那一下选区就没了,颜色打不上;打开时先把选区存下来 */}
<Popover open={panel} onOpenChange={setPanel} trigger="click" placement="bottomLeft" arrow={false}
content={
<div className="rt-panel" role="menu" aria-label="文字颜色" onMouseDown={(e) => e.preventDefault()}>
{RICH_COLORS.map((c) => (
<button key={c.code || "default"} type="button" role="menuitemradio" aria-checked={active.color === c.code}
className={"rt-sw2" + (active.color === c.code ? " on" : "")} title={c.name} aria-label={"文字颜色:" + c.name}
onClick={() => applyColor(c.code)}>
{/* 面板只给色块,不写中文(颜色本身会说清楚);名称留在 title / aria-label 里 */}
<span className="rt-chip" style={c.code ? { background: "var(--" + c.code + ")" } : undefined}>
{c.code ? null : <i className="rt-slash" aria-hidden="true" />}
</span>
</button>
))}
</div>
}>
<button type="button" className={"rt-btn rt-color" + (active.color ? " on" : "")}
aria-haspopup="menu" aria-expanded={panel} title="文字颜色" aria-label="文字颜色">
<span className="rt-awrap">
<span className="rt-a">A</span>
<span className="rt-fill" style={{ background: active.color ? "var(--" + active.color + ")" : "var(--text)" }} />
</span>
<Icon name="chevron-down" size={11} className="rt-caret" />
</button>
</Popover>
<button type="button" className="rt-btn" title="清除格式(Ctrl+\\)" aria-label="清除格式" onClick={clearFormat}>
<Icon name="eraser" size={15} />
</button>
</div>
<EditorContent editor={editor} />
</div>
);
}

View File

@ -0,0 +1,12 @@
import { hasRichMarks, sanitizeRich, textToHtml } from "../utils/richtext";
/**
* 正文展示:一律过一遍消毒再注入(内容是用户数据,不能直接 innerHTML)。
* 旧数据是纯文本,走同一条路(只把换行变成 <br>),所以调用方不用区分。
* 需要纯文本的地方(关键字高亮、导出、AI)用 utils/richtext 的 richToText。
*/
export function RichText({ value, className }: { value?: string | null; className?: string }) {
const html = hasRichMarks(value) ? sanitizeRich(value) : textToHtml(String(value || ""));
if (!html) return null;
return <span className={"rich-view" + (className ? " " + className : "")} dangerouslySetInnerHTML={{ __html: html }} />;
}

View File

@ -0,0 +1,139 @@
import { Button, Input } from "antd";
import type { InputRef } from "antd";
import { useEffect, useMemo, useRef, useState } from "react";
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
import { Icon } from "../icons/Icon";
import { useCan, useSession } from "../store/session";
import { useUi } from "../store/ui";
import { useDebounced } from "../utils/hooks";
import { ProfileModal } from "./ProfileModal";
import { PageHead, VIEW_META } from "./PageHead";
import { PeriodPicker } from "./PeriodPicker";
import { UserChip } from "./UserChip";
const NAV: { key: string; label: string; icon: string; group?: boolean }[] = [
{ key: "board", label: "工作看板", icon: "board" },
{ key: "projects", label: "自研产品", icon: "list-checks" },
{ key: "custom", label: "定制项目", icon: "package" },
{ key: "focus", label: "每周工作", icon: "target" },
{ key: "staff", label: "人力资源", icon: "users", group: true },
{ key: "intake", label: "更新录入", icon: "pencil" },
{ key: "settings", label: "设置", icon: "sliders" },
{ key: "rbac", label: "权限管理", icon: "shield-check" },
];
// 顶栏控件按视图给(旧版 setView 里同一份名单):周期选择器只对按周/月统计的页面有意义,
// 搜索框对设置 / 权限 / 录入没有作用;定制项目的「年度任务」页签也藏起来(旧版 renderCustom 里那一行,年度表不吃关键字)。
const PERIOD_VIEWS = ["board", "projects", "custom", "focus", "intake"];
const SEARCH_VIEWS = ["board", "projects", "custom", "focus", "staff"];
/** 应用外壳:侧栏(品牌 / 菜单 / 用户)+ 顶栏(周期 / 全局搜索 / 深浅色切换)+ 视图区。
* 菜单用真链接(NavLink 自带 aria-current="page"),<=1100 转抽屉;收拢态只留图标 + 名称气泡。
* 顶栏原「更新录入」入口已按需求移除——侧栏「支撑 · 更新录入」与看板/卡头的录入入口都还在。*/
export function Shell() {
const nav = useNavigate();
const loc = useLocation();
const view = (loc.pathname.split("/")[1] || "board").replace("/", "");
const { r } = useCan();
const me = useSession((s) => s.me);
const folded = useUi((s) => s.navFolded);
const theme = useUi((s) => s.theme);
const keywordStore = useUi((s) => s.keyword);
const customTab = useUi((s) => s.customTab);
const setKeyword = useUi((s) => s.set);
const [mobileOpen, setMobileOpen] = useState(false);
const [profileOpen, setProfileOpen] = useState(false);
const [input, setInput] = useState(keywordStore);
const searchRef = useRef<InputRef>(null);
// 320ms 防抖后写入全局状态(与旧版 bindKeyword 同口径):顶栏输入、八个视图共用同一个关键字
const debounced = useDebounced(input);
useEffect(() => {
// 换视图、或顶栏没在编辑而被别处(卡头搜索框)改动时,回到全局关键字
const el = searchRef.current?.input;
if (el && document.activeElement === el) return;
setInput(keywordStore);
}, [loc.pathname, keywordStore]);
useEffect(() => {
const next = debounced.trim();
if (next !== keywordStore) setKeyword({ keyword: next });
}, [debounced, keywordStore, setKeyword]);
useEffect(() => setMobileOpen(false), [loc.pathname]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setMobileOpen(false); };
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, []);
const allowed = useMemo(() => NAV.map((n) => n.key).filter((k) => r(k as never)), [r, me]);
useEffect(() => { if (allowed.length && !allowed.includes(view)) nav("/" + allowed[0], { replace: true }); }, [allowed, view, nav]);
const visible = NAV.filter((n) => allowed.includes(n.key));
return (
<>
<a className="skip-link" href="#mainContent">跳到主要内容</a>
<div className={"app" + (folded ? " nav-folded" : "")}>
<aside className={"sidebar" + (mobileOpen ? " open" : "")} id="sidebar">
<div className="brand">
<div className="brand-mark"><Icon name="target" /></div>
<div className="brand-text">
<h1>DMS管理平台</h1>
<span>软件开发部</span>
</div>
<button className="nav-fold" aria-label={folded ? "展开菜单" : "收起菜单"} aria-expanded={!folded} aria-controls="nav"
onClick={() => useUi.getState().set({ navFolded: !folded })}>
<Icon name="panel-collapse" className="ic-fold" />
<Icon name="panel-expand" className="ic-unfold" />
</button>
</div>
<nav className="nav" id="nav" aria-label="功能菜单">
{visible.filter((n) => !n.group).map((n) => <NavItem key={n.key} n={n} folded={folded} />)}
<div className="nav-group" role="group" aria-labelledby="navGroupSupport">
<div className="nav-label" id="navGroupSupport">支撑</div>
{visible.filter((n) => n.group).map((n) => <NavItem key={n.key} n={n} folded={folded} />)}
</div>
</nav>
<div className="side-user"><UserChip onOpenProfile={() => setProfileOpen(true)} /></div>
</aside>
<div className={"nav-mask" + (mobileOpen ? " open" : "")} onClick={() => setMobileOpen(false)} aria-hidden="true" />
<main className="main" id="mainContent" tabIndex={-1} aria-label={(VIEW_META[view] || [view])[0]}>
<header className="topbar">
<Button className="nav-toggle" type="text" aria-label="打开功能菜单" aria-expanded={mobileOpen} aria-controls="sidebar"
icon={<Icon name="menu" />} onClick={() => setMobileOpen((v) => !v)} />
{PERIOD_VIEWS.includes(view) && <PeriodPicker />}
<div className="topbar-right">
{SEARCH_VIEWS.includes(view) && !(view === "custom" && customTab === "annual") && (
<Input ref={searchRef} className="search" type="search" allowClear aria-label="搜索项目或内容" placeholder="搜索项目 / 内容…"
value={input} onChange={(e) => setInput(e.target.value)} />
)}
<Button className="theme-toggle" type="text"
aria-label={theme === "dark" ? "切换到浅色主题" : "切换到深色主题"}
title={theme === "dark" ? "切换到浅色主题" : "切换到深色主题"}
icon={<Icon name={theme === "dark" ? "sun" : "moon"} />}
onClick={() => useUi.getState().set({ theme: theme === "dark" ? "light" : "dark" })} />
</div>
</header>
<div className="views">
{visible.length === 0
? <>
<PageHead title="没有可见菜单" desc="当前角色的权限不足,无法打开任何功能页。" />
<div className="notice warn" role="alert"><Icon name="alert-circle" className="ti" /><div>当前角色没有分配任何功能菜单,请联系管理员在「权限管理」里授权。</div></div>
</>
: <Outlet />}
</div>
</main>
</div>
<ProfileModal open={profileOpen} onClose={() => setProfileOpen(false)} />
</>
);
}
function NavItem({ n, folded }: { n: { key: string; label: string; icon: string }; folded: boolean }) {
return (
<NavLink to={"/" + n.key} data-tip={n.label} aria-label={folded ? n.label : undefined}
className={({ isActive }) => "nav-item" + (isActive ? " active" : "")}>
<span className="ni"><Icon name={n.icon} /></span>
<span className="nl">{n.label}</span>
</NavLink>
);
}

Some files were not shown because too many files have changed in this diff Show More