feat: 新增手机端完整交互界面与流程终止配置功能

新增手机版式专用的顶栏、底表、下拉刷新、通知面板等组件,适配窄屏交互;新增流程终止配置功能,支持发起人终止权限控制与终止时写回模板配置;新增构建号注入机制,用于镜像与前端版本一致性校验;优化数字等宽字体、字号适配等移动端样式。
main
kangwenjing 2026-11-04 15:25:17 +08:00
parent ae3f544fd6
commit db917805b8
120 changed files with 15970 additions and 495 deletions

View File

@ -46,6 +46,12 @@ FROM --platform=$BUILDPLATFORM node:24-bookworm-slim AS web
# 换源加速(国内网络建议在 docker-compose.yml 里覆盖成 npmmirror)
ARG NPM_REGISTRY=https://registry.npmjs.org
# 构建号:手机首页右上角显示的就是它。打镜像时与 tag 用同一个值——
# docker build --build-arg OA_APP_BUILD=202611031830 -t …:202611031830 .
# 于是手机上那一串 == 集群里那个 Pod 的镜像 tag。留空则退回构建那一刻的时间戳。
ARG OA_APP_BUILD=
ENV OA_APP_BUILD=${OA_APP_BUILD}
WORKDIR /src
COPY frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml frontend/.npmrc ./
# pnpm 版本跟着 package.json 的 packageManager 走(lockfile 是谁生成的就用谁装,

188
README.md
View File

@ -130,9 +130,12 @@ unisoa/
├── docs/node-writeback-config.md # 中间环节写回怎么配:到达时 / 审批通过后 / 被退回时 / 被撤回时、只发部分单据、失败卡控与边界
├── docs/goback-target-writeback-design.md # 「本环节被退回时」再筛两道:退回到哪个环节才发、这一退是谁按的(含第三方调接口退回)
├── docs/integration-contract.md # 给上游看的接口契约:字段、金额单位、幂等键、批量与对账口径
├── docs/expense-thirdparty-field-update.md # 费用报销:财务在第三方改审定金额怎么回写 OA(decide 带 data、生产配置与可写字段清单)
├── docs/platform-open-api-design.md # 开放平台:外部系统调 OA 的钥匙 / 作用域 / 限流 / 留痕,与事件推送的分工
├── docs/notification-channels-design.md # 消息渠道:邮件与钉钉/飞书/企微群机器人,投递留痕、退避重试与死信
├── docs/mobile-pwa-design.md # 移动端:为什么是 PWA、离线外壳只兜底不缓存接口、底部导航与安全区
├── docs/mobile-approval-layout.md # 手机端审批版式:只换版式不换逻辑、首页五张卡片、四问抬头、表单三层归置、bottom sheet
├── docs/mobile-form-layout-config.md # 手机端表单版式配置:手机上只出一节,摆哪几格、什么顺序、每格怎么摆都能配(存 layout.mobile,没动后端)
├── docs/process-intervention-design.md # 流程干预:挂起 / 改道 / 整单催办改派 / 修正表单,边界与留痕口径
├── docs/draft-create-api.md # 创建流程草稿接口:一个接口建任意类型草稿、参数清单怎么查、外部系统怎么代人铺单
├── docs/multi-worker-deployment.md # 多副本部署:调度租约、启动命名锁、建库白名单与还没拿掉的单进程假设
@ -1799,8 +1802,19 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
同时管办结与终止,不用再复制两份映射),**也可以一条都不勾**——那不算是没配完,是时机还没定:
这条模板要么被挂在某个环节上,要么只在集成页人工重推。环节那一刻的时机、条件、要发的字段、失败
策略全在 L3 那一格。模板页底部当场给出「什么时候真的会发」= 勾中的终态 + 被挂在哪些环节的哪一时刻,
两处合起来才是答案;存量那批「模板自己点名到达某环节」的配置照旧发,页面上一个按钮把它们一次搬进
环节(写挂载与撤声明同一事务,中间不留"两边都没配"的空档)。
环节(写挂载与撤声明同一事务,中间不留"两边都没配"的空档)。除这两处之外还有**第五个时刻**:
「流程终止时」既不挂环节(终止不是画布上的一环),又不能只写在模板上(终态模板按**绑定表单**自动找齐,
同一张表单挂两条流程时,"终止时要通知上游"没法只给其中一条配),所以它配在流程自己身上——
`流程设计 → 流程信息 → 终止`,形状与环节挂载完全一致,只是时刻固定 `terminate`。
`trigger_of` 认 `terminate` / `terminated` 两种写法,幂等键里带 `event_key=terminate` 这一段,与模板
自己勾了终止那条(`event_key` 为空)天然两个键:**同一个模板两处都配就各发一条**,设计器与保存流程时
都会就地提醒,不替人猜要发几条。这一格也算**第三处绑定点**:模板页底部那份「什么时候真的会发」如今
合并四处(模板勾的终态 + 旧写法点名的环节 + 环节挂载 + 流程这一格终止挂载),少合并一处就是在这屏
对着人说"这条模板终止时不会发"而它其实每次都发;集成页的配置体检也扫这一格(模板是保存**之后**才被删、
被停用的,保存那道闸管不到)。细节见下一节与 `docs/node-writeback-config.md` §1 §3 §5.5.1。
**退回与撤回也是触发点**:界面上有「退回」「撤回」两颗钮,报文里以前却没有这两个时刻——想告诉上游
"这张单被打回去了",只能挂到收单那一环的「到达时」,归属当场错位(对面分不清是正常到达还是被打回)。根因是
@ -1833,10 +1847,75 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
设计期把写歪的配置挡在保存之前,前后端同一把尺子:字段不存在、明细表指错、
幂等键少了模板编码、响应回写的字段审批人还能改、环节挂的模板已被删——都当场说清楚。
口径与缺口见 [docs/outbound-integration-design.md](docs/outbound-integration-design.md),
给上游看的接口契约见 [docs/integration-contract.md](docs/integration-contract.md)。
对账(按天问上游「今天有哪些单」与发件箱比差异)与灰度压测还没做,缺哪几项写在那份文档 §14。
上面那一整节讲的都往外走的**正常路径**:单子一级级批上去、批完定局、发凭证。「终止」是这条路上
唯一一处**没走正常路径就散场**的时刻,而它既不是一条路由、也不是画布上的一个环节,挂不到任何一环上,
所以「终止那一刻要调用哪几条回写模板」以前没地方配。它自己占一节,见下一节。
### 流程终止:谁能按、按到什么时候为止、按下去要发什么
起因是一张真实的报销单(2026-11-04):单子已经走到「部门主管」,主管一次都没打开过待办,发起人自己在
「我发起的」把整张单终止了,第二天主管来问"为什么给我终止了"。审批记录上那一行是红底一枚「终止」、
处理人写着主管本人、意见栏写着「流程终止」,谁都读得出是主管终止了自己的审批。读错的原因在档案表上:
终止前引擎要把当时还挂着的待办逐张强行结掉再归档,归档行照旧落在**原持有人**名下(他的已办里得看得见
这张单),而这张表压根没有一列写"是谁按的终止",意见那一格又拿系统兜底那四个字填上了发起人留空的原因。
终止这个动作一直是**发起人随时能按**——单子哪怕跑到最后一环、在别人手上搁了三天也照样能按,按下去可以
不留原因、不通知任何人、上游业务系统也不知道这张单没了。现在这三件事都能在流程上说一句。
入口两处在**流程设计**里,模板本体仍在集成页:
| 配在哪 | 配什么 | 落在哪 |
| --- | --- | --- |
| 流程设计 → 流程信息(meta 面板)→「终止」 | 发起人的终止钮开不开、到什么时候为止不再许他终止、终止那一刻调用哪几条回写模板 | `oa_process.terminate_config` |
| 流程设计 → 选中环节 →「允许终止」 | 单据**正停在这一环**时发起人能不能终止(与「允许退回」「允许撤回」同一开关家族) | `oa_activity.config.allowTerminate` |
「允许终止」这一格以前就有,但只是一句谎话:接口把它回给前端、类型里也写着,设计器没有对应的勾,
前端没有任何一处读它,引擎更不看它——关掉了照样终止得动。现在它是引擎尊重的硬闸。
窗口四档**单选**(`until`):
| `until` | 什么时候之前还允许发起人终止 | 用在什么场合 |
| --- | --- | --- |
| `always`(默认) | 随时都能 | 出厂口径,与这套配置存在之前一字不差 |
| `notHandled` | 别人(不含发起人自己)还没办完过任何一步 | 单没落到任何人手上时,终止与撤回没多大分别;有人签了字就该走「退回」 |
| `beforeActivity` | 还没走到指定环节(**含**这一环) | 「过了部门主管这关就别想反悔」。判据是**到过**,不是"还停在那儿"——单子从那一环流走之后再让终止,前面那位主管的表态就白做了 |
| `withinHours` | 发起之后 N 小时之内(1-8760) | 报销单隔夜就没人再动,专治"第二天想起来才反悔" |
三条口径先说死,免得日后当成 bug 提:
- **只管发起人,不管管理员**。监控页那颗「终止」是干预手段(单子办错了要收尾),与发起人收拾自己
交出去的那张单是两件事;管理员与 `/open/*` 那两条路只受"是不是发起人或管理员"这一条老约束。
- **关掉就是界面不出现 + 引擎同样挡**。只藏按钮不挡接口,等于留一个能绕过规矩的口子;只挡接口不藏
按钮,用户要点一次才知道不让。「我发起的」列表、单据详情、手机端三处读的都是引擎那一份判据
(`service/terminate.starter_blocker`),界面上那句"为什么按不动"与引擎挡下时抛的那一句同源。
列表那一档只看开关(每行多算一次窗口要问库,代价不值),窗口类的判据留给详情页与引擎。
- **`until` 是单选,不是能叠的清单**。四档各有各的用处,叠起来的解释成本比收益高;既想"过某环节"
又想"超 N 小时",就挑更严格的那一条写清楚。
按下去之后引擎做五件事(原来只有前两件):
- 把还挂着的待办逐张结掉归档,并在档案行上写明**是谁终止的**(`oa_task_completed.operator` /
`operator_name`;本人自己办的那些照旧留空,两者分得开);
- 往流转日志旁挂一条 `terminate` 留痕,把操作人与原因落在单子上——审批记录据此在那一行下面显示
「由 X 终止」,读者不会再以为处理人自己撤了;
- 给每一个**待办被清掉**的人发一条站内信。以前终止只给发起人自己发一句「流程已办结」,被清掉的人那边
永远挂着一条"等待您在【部门主管】环节处理",点进去是一张已归档的单,谁都不知道还要不要办;
- 按流程那一格入队写回,与终止同一事务(`event=terminated`、`event_key=terminate`);
- 照旧处理冲销:配了「冲销模板」就自动反向冲一条,没配就只在原报文上挂 `needs_reversal` 让人工去上游
收尾,机器不猜这张凭证该不该作废。
终止原因在界面接口上改成**必填**(管理员干预与开放接口保留默认文案),空着时那四个字「流程终止」
再也不会冒充别人的意见。存量流程一条都不用迁移:`terminate_config` 空 dict 就等于"发起人随时能终止、
终止时不多发一条写回"。生产库上线要先跑 `sql/upgrade/20261104_terminate_config.sql`(加那三列;没开
`auto_create_schema` 时新后端读 `oa_process` 就会报 `Unknown column`)。判据只有一份,在
`backend/app/service/terminate.py`;验收 `backend/scripts/check_terminate_control.py` 全程跑在内存
sqlite 上(55 项:谁按得动、窗口怎么算、留痕与通知、终止那一刻的写回与冲销、这一格在合并清单与全库体检里
看得见、列表那一列的开关),一条语句都不碰生产库。
### 反过来:外部系统怎么调 OA,OA 怎么主动通知人
上面那条是"审批结果送出去"的**业务凭证**那一路(报文格式由上游定、发错要冲销)。
@ -1868,6 +1947,76 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
免得获得焦点时页面自己放大。装之前要 HTTPS(内网用自签证书也行,手机得装上根证书)。
边界与真机验收清单见 [docs/mobile-pwa-design.md](docs/mobile-pwa-design.md)。
### 手机上把单子批掉(竖屏版式)
从企微卡片点进来的多半是待办详情,那一页在 <768 的屏上换一套版式:抬头先答完四问
(这一单是什么、谁提的、多少钱、卡在哪一步几号到期),本环节要填的格子提到最前,
四十几格按类型归置——空值不渲染、系统取数折成一行、明细收成「12 条 · 合计」,
底下只吸三颗:`同意` / `退回` / `···`,办完直接跳下一条。弹层一律从屏幕下沿推上来,
每条出口上写着它去哪儿。**判据只有宽度,而且只作用于版式**:审批逻辑仍是桌面那一份
(`TaskDetailView` provide 出去,`components/oa/mobile/` 只负责摆),后端零改动。
手机上打开系统第一眼就是这一屏:`utils/returnPath.ts` 的 `landingPath()` 按设备挑表、再按权限挑那条真进得去的
——手机上 工作台 → 待办 → 我的 → 门户,桌面照旧门户第一。「普通员工」那一档没有 `work:workbench`,
写死落 `/workbench` 只会被守卫打回门户新闻页,那看着就像手机版式没做;这类人现在落进待办那张卡片流。
门户在抽屉侧栏里仍点得到。
首页那一屏(`/workbench`)在手机上换成五张小卡片——`待办` / `已办` / `待阅` / `已阅` / `我发起的`,
一张对一个列表,数字与点进去那张列表同口径(待办待阅取角标那份计数,已办与我发起的取工作台统计,
已阅取已阅列表的 total);底部标签栏只剩 `首页` / `待办` / `我的` 三格,「发起流程」搬到首页那五张
卡片底下那颗钮。桌面上那套统计卡 + 快捷发起 + 概览走 `v-else`,一行没动。
手机上那条顶栏(汉堡 + 站点名 + 通知 + 语言 + 深色 + 头像)整条不挂了,在 390 上它比正文还高:
子页面只留一行 44px 的细栏(`components/layout/MobileTopBar.vue`:返回 + 页名,底部三格那几页连细栏都不要),
其余几件事各有去处——通知是首页抬头那颗铃铛与「我的」那一行(同一张底部弹层)、语言/深色/字号在
「我的」→ 外观、其余入口在「我的」按权限分组列出、退出也在那儿。左侧那个抽屉在手机上整块不挂(`AppSidebar v-if="!phoneShell"`,它的拉手本来就在顶栏那颗汉堡上;
768~1023 那一档汉堡与抽屉照旧)。「我的」这一格(`ProfileView.vue` 手机档)
因此是新画的一屏:身份、通知、收款账户、入口几组、外观、添加到主屏幕、退出,末尾钉着构建号;
桌面上那一版一个字没动。详情抬头砍到一行(左边几枚徽章、右端一枚发起人标,单号挪到审批记录末尾),
审批记录换成 `components/oa/mobile/MobileFlow.vue` 那条竖向时间线(默认只摆最近三步、发起那一行永远留着、
末尾高亮「此刻卡在谁手上」,数据仍出自 `utils/approvalRecord`),更多操作里去掉「打印审批单」,
提示条贴底居中且不摆关闭叉,登录成功那一句在手机上不发。
**详情页不给「打印审批单」也不给「刷新」**:打印是回到电脑上的事;刷新那颗图标在屏幕最上沿、
离拇指最远,撤掉之后换成 `composables/useMobileRefresh.ts` 两条道——往下拉这一把手势
(`usePullToRefresh`:只到顶继续下拖才接管,顶栏正中浮一枚「继续下拉 / 松开刷新 / 正在刷新…」的胶囊;
待办详情只认主动下拉,免得抹掉正在填的字),加上只读那一屏回到前台自己取一次
(`useRefreshOnReturn`)。列表页与首页仍留那颗刷新按钮,那是几十条数据的入口,得给个显式口子。
单据详情那一屏(`/work/:job`:已办、我发起的、待阅、通知弹层、流程监控点进来是同一个落点)原先只有
桌面那一版,从「我发起的」点开自己提的单子看到的还是那一整块说明——`按第 13 版设计在走`、
`流程名 · 单号 · 发起人:×(部门)`、`发起时间`、`打印审批单 / 刷新 / 催办 / 终止流程` 摊两排——
所以它也分了两档(`components/oa/mobile/MobileWorkView.vue`,只读):那一整块在手机上一个字都不摆,
抬头就一行(徽章 + 右端发起人标)加关键数字,「表单内容 / 审批记录」两页签,画布换成同一条竖时间线
但不给批注框,吸底那一行只在真办得动时才挂、且只那一颗(`提交发起` / `催办`),
`流程干预`(要 `monitor:work`)、`终止流程`、看电脑版与字号全收进顶栏那个 `···`,
两个要写意见的都在下推层里写;这一页同样标了 `meta.chromeless`。判据仍由 `WorkDetailView` 一处算完
递下去,桌面那一版(同一个文件的 `<div v-else>`)一个字没动。
手机上「完整单据」那一屏不再借桌面的 `FormRenderer`(它的段头位置按桌面 12 列网格的行号算,
390 上全错配,几段的段头会一起堆到最顶上),换成 `components/oa/mobile/MobileFormReader.vue`:
一格一行、空着也留一行、**分节先认页签名再认分隔条**(生产上那张费用报销单就是靠一张「标签页」
分两页的,原先这一层只认分隔条,三十几格全挤进一节「表单内容」),外部系统那一页整节给一张
「打开」卡片。哪几格上这一屏现在能在表单设计器里逐格定:属性面板「默认隐藏」旁边多了
「**手机上不展示**」(`field.mobileHidden`,只影响手机版式,电脑 / 打印 / 导出 / 必填照旧,
画布上挂 `手机不展示` 角标;框选一片还能用多选面板那两颗一次收掉——那张报销单 32 格,逐格点没人受得了)。
新键由后端原样存回,**没动后端一行**。
手机上「表单内容」那一屏原先只能做减法(逐格藏),摆成什么样定不了——一句原话是「表单内容里
分费用报销基本信息、系统取数、完整单据,我就希望只有费用报销基本信息,但里面展示哪些字段、
怎么排放要有地方配」。表单设计器工具栏因此多了一颗「**手机端**」(角标写此刻是「自动」还是
「已配置」):勾上「按这份配置展示」,手机上就**只出一节**,节名、哪几格上屏、从上到下的顺序、
每格的摆法(一行 / 整段 / 置顶大字 / 缩略图 / 只写数量 / 收成一行 / 逐条展开)在那张清单里一次配完,
两颗粒子改一格;清单上那颗「展示 / 不展示」写的还是格子上的 `mobileHidden`,与属性面板那颗同源。
配置存在 `content.layout.mobile`,**后端一行没动**(`clean_formats` 原样存回 `layout` 里的东西)。
没勾这一档的表单走的还是上面那套按字段类型的自动归置,一个字没变;勾了之后环节字段权限、
整单「默认隐藏」、本环节要填的那几格三道闸照旧,末尾「完整单据」按配置给不给——不给的话
那条路收进顶栏的 `···`,要的是"只有一节",不是"这一单在手机上看不全"。
取舍、口径与验收见 [docs/mobile-form-layout-config.md](docs/mobile-form-layout-config.md)。
另一处顺手修的:没配核验闸门的单子不再摆「外部核验」那块面板(后端一直发着 `configured`,
是前端没认;真送过一次审的单子仍然照摆)。
预览台 `frontend/preview-mobile.html`(dev only,`screen=home|list|detail|work|profile`,
`form=tabs` 换成生产上那张分页 + 外部页面的报销单,`form=custom` 换成配了手机端版式那一档
(只出一节)作对照,`screen=panel` 单摆设计器那个「手机端」面板,`open=reader` 直接把「完整单据」点开),
设计稿 `design/mobile-approval.html`,取舍与验收见 [docs/mobile-approval-layout.md](docs/mobile-approval-layout.md)。
发版有没有生效不用猜:首屏问候语下面那串 12 位数字就是构建号,构建时 `--build-arg OA_APP_BUILD=$TAG`
把镜像 tag 烤进产物,手机上那一串跟 `kubectl get deploy` 里的 tag 对上,就说明这台手机跑的就是这一版。
更多操作里点过「看电脑版」的,底部标签栏头顶会多一颗「看手机版」把它退回来。
### 多副本部署(`--workers N` / 两台机器)
后台任务不再默认"只有一个进程在做":**谁拿到库里的租约谁跑**(`oa_worker_lease`,
@ -1911,8 +2060,8 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
两个开关加一条手改保护管住标题归谁说了算:
- `editable` 关掉后发起页的标题框只读,规则算成什么样就是什么样;
- `refresh` 打开后,后面环节改了表单字段会按同一规则重算,在途待办的标题一起改
(待办列表与站内信读的都是 `task.title`);
- `refresh` 打开后,后面环节改了表单字段会按同一规则重算,在途的待办与待阅一起改名
(待办列表、待阅列表、站内信读的都是各行自己那一份 `title`,不回查单据);
- 发起人亲手改过的那句记在 `work.variables.titleManual`,开了自动重算也不盖他写的。
**标题也可以是表单里的一个字段。** 想让用户在单据表单里看得见、改得动标题,就去
@ -1925,8 +2074,11 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
`manual` 由发起人自己填(比流程级开关更具体,规则只在这一格空着时补一句);
- 发起页里这一格随表单实时重算:没人动过它时,改了别的字段它就跟着规则换一句;
亲手改过之后不再被规则盖掉;
- 后续环节里改这一格等于改标题:引擎采纳他写的这句、同步下一环节待办,并从这一刻起
- 后续环节里改这一格等于改标题:引擎采纳他写的这句、同步在途的待办与待阅,并从这一刻起
不再自动重算(等同 `titleManual`);谁能改由该环节的「表单字段权限」决定;
- 管理员在流程监控的「修正表单」里改这一格同样算改标题:走的是与办单同一句 `titles.refresh`
(`engine._refresh_title`),单据、在途待办、待阅三处一起改名——已办 / 已阅不动,
那是那个人当时批过的快照;判据 `scripts/check_intervention_title.py`;
- 存草稿取同一句:这一格写着什么,拟稿箱里就叫什么,发起前后不会换名字。
**规则界面上只有一处可配。** 就在表单那一格上(`field.titleRule`):
@ -1971,8 +2123,8 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
`{流程名称}` 依次借所属流程的名字、画布上这个表单名、库里那张表单的名字顶上。
两个设计器都只读这几个接口,不自己拼变量表。
**标题是随表单实时走的,不是发起那一刻算完就定死。** 三个地方都在改完那一下当场换一句
(`composables/useAutoTitle.ts` 一份实现,三处共用;口径仍是 `service/titles.py`):
**标题是随表单实时走的,不是发起那一刻算完就定死。** 四个地方都在改完那一下当场换一句
(发起页与设计器那份在 `composables/useAutoTitle.ts`,一份实现共用;口径仍是 `service/titles.py`):
- **发起页**:表单里那一格随填随改,公式、带出、级联算完的值都算得进来;
- **表单设计器的「预览」页**:填两个字段就能看到规则跟着动,配完不必先保存再发起一张测试单。
@ -1980,13 +2132,16 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
- **办理页**:后面那一环改了表单字段、而规则又开了「自动重算」时,标题框下面写一句
「提交后会更新为 …」——只说,不写回。提交之前那一句还是上一个环节的,改了字段就当场改口
会让人以为已经改了。
- **监控页的干预面板「修正表单」**:管理员改完那几格,表单下方写一句「保存后标题会变成 …」,
说的就是 `fix_data` 落库那一刻会做的那一步——同样只说,不提前写回。
三处守的是同三条分寸:**只覆盖系统自己写的那一句**(字段里是人亲手写的就原样留着,
这几处守的是同三条分寸:**只覆盖系统自己写的那一句**(字段里是人亲手写的就原样留着,
规则收了修改权限时反过来——那一格归规则说了算);**没人动过的标题格在问后端之前先从数据里
摘掉**(否则规则再怎么改,后端念回来的都是上一轮那句老的,标题从此不再跟着表单走);
**防抖 + 迟到不回写**(一路打字只问一次,回来的答案只配给当下这份数据)。
办理页那一句走 `POST /job/{job}/title/preview`:按这一单此刻的数据 + 将要提交的那份改动算,
只读不写库,也没办过的人(发起人、有待办的人)都能问。
办理页与干预面板那一句走 `POST /job/{job}/title/preview`:按这一单此刻的数据 + 将要提交的那份
改动算,只读不写库。问得动的人:发起人、手里有待办的人,以及监控页数据范围里看得见这张单的人
(有 `monitor:work` 时按 `/admin/work/{job}/data` 同一道数据范围筛判)。
## 接口一览
@ -2034,7 +2189,17 @@ python3 scripts/audit_storage.py --to-minio # 把本该进 MinIO
PWA 与窄屏:`public/manifest.webmanifest` + `public/icons/`(`scripts/gen-icons.py` 生成)、
`sw.template.js`(构建时发成 `dist/sw.js` 并盖版本戳,见 `vite.config.ts` 的 `serviceWorkerPlugin`)、
`composables/usePwa.ts`(接住安装事件、点刷新才接管)、`composables/useMobileNav.ts`
(与 Tailwind `lg` 同一条断点、底部要让出的高度)、`components/layout/MobileTabBar.vue`
(与 Tailwind `lg` 同一条断点、底部要让出的高度)、`components/layout/MobileTabBar.vue`;
竖屏审批版式:`composables/useMobileShell.ts`(手机版式总闸 `<768`、`chromeless` 判据、
字号三档与「看电脑版」)、`composables/useMobileRefresh.ts`(详情页没有刷新按钮之后怎么取新数据:
下拉手势的接管条件与回到前台补一次)、`components/oa/mobile/`(`MobileTaskView` 只排版式,
`taskContext.ts` 是它与 `TaskDetailView` 之间唯一的接口,`useFormPlan.ts` 管表单怎么归置
(摘要 `planForm` 与「完整单据」`readerSections` 两份共用同一套页签 / 分隔条分节判据),
`MobileFormReader.vue` 是「完整单据」那一屏的手机原生读法(一格一行、空值也留、外部页面那节给一张卡片),
`MobileWorkView.vue` 是手机上那张只读单据详情(`/work/:job`),
`MobileFlow.vue` 是手机上那条竖向流转时间线、`MobileHome.vue` 是首页那五张卡片,
`MobileNotificationSheet.vue` 是读通知那张弹层,未读数与桌面顶栏共用 `stores/app.ts` 里那一份)、
`components/layout/MobileTopBar.vue`(手机上替代整条顶栏的那一行 44px:返回 + 页名)
- 权限层:`constants/permissions.ts`(权限码分组与中文名)、`stores/auth.ts` 的
`can/canAny/dataScope/roleNames`、`api/authrole.ts`、`views/oa/org/AuthRoleListView.vue`
(权限矩阵 + 成员勾选);`AppSidebar.vue` 按权限过滤菜单,路由守卫按 `meta.permission` 放行
@ -2105,6 +2270,8 @@ python3 scripts/check_writeback_revisit.py # 环节写回重发:提交时/到
python3 scripts/check_writeback_trigger.py # 「什么时候发」拆两处:终态可多勾 / 一条都不勾是合法态 / 旧写法一键搬进环节(跑完自己删干净)
python3 scripts/check_outbox_wake.py # 写回什么时候真的发出去:入队提交当场叫醒 / 回滚不空叫 / 一轮发干净一张单(影子模式,跑完自己删干净)
python3 scripts/check_writeback_config.py # 写回配置全库体检:先报现库哪几条会静默不发/多发,再把八种病各造一遍自证(--report 只报不当闸门)
python3 scripts/check_terminate_control.py # 终止管不管得住:谁能按、四档窗口、留痕与通知、终止那一刻的写回与冲销(内存 sqlite,不碰生产库)
python3 scripts/check_schema_snapshot.py # sql/schema.sql 与 models.py 有没有走散
python3 scripts/check_schema_bootstrap.py # 动过启动建表补列(app/db.py::create_schema):空库建齐 + 拆坏能补回,自建临时库
python3 scripts/check_index_gaps.py # 动过索引 / models.py 的 __table_args__ / 新写了 WHERE 里等值过滤:会长大的表上不能没索引还没理由
@ -2145,6 +2312,7 @@ python3 scripts/check_log_timeline.py # 动过流转日志留痕
python3 scripts/check_completed_dedup.py # 动过「我的已办」按单折叠(app/service/completed.py 与四处计数):全程在未提交事务里跑,库里不留行
python3 scripts/check_delete_unstarted.py # 动过「删除还没发起的单」(engine.delete_unstarted / deletable_task_ids / POST /job/{job}/delete,含删单那一刻给第三方那一句通知):建自己的流程与单据,跑完删干净
python3 scripts/check_begin_resubmit_todo.py # 动过开始环节提交(engine.start_from_begin:界面那颗「提交」、第三方 auto 回写、发起人确认第三方备好的表态三条路共用):退回到发起人再提交之后,这张单在「我的待办」里只许留一条,且这一步照常进已办与审批记录(建自己的流程与单据,跑完删干净)
python3 scripts/check_intervention_title.py # 动过干预「修正表单」与标题的联动(engine.fix_data / _refresh_title / titles.sync_pending_titles / titles.preview_refresh):人填、自动重算、不重算三种口径各跑一张真单子,改完待办 / 待阅 / 监控三张列表一起对得上,保存前的预告也一并校(自己建流程自己删)
python3 scripts/check_serial_timing.py # 动过编号时机(numbering.timing_* / engine.issue_serial / drafts.reserve_serial):五档时机各跑一张真单子(create 那一档连凭条三道闸一起跑),自己建流程自己删
python3 scripts/check_leader_lease.py # 动过跨进程租约(app/service/leader.py)/ 准备开 OA_WORKERS 多进程
python3 scripts/check_outbox_wake.py # 动过写回投递时机(service/outbox.py 的 wake / run_due / refresh_pending,或 main.py 调度线程的睡眠与叫醒)

View File

@ -14,7 +14,7 @@ from ..db import get_db
from ..deps import CurrentUser, actor_of, current_user, require_permission
from ..engine import definition as definition_module
from ..service import (autofill, dedupaudit, dicts, fetch, formruntime, mapping, node_approve, numbering, org,
quota, simulator, starters, threshold, titles)
quota, simulator, starters, terminate as terminate_service, threshold, titles)
from ..engine import engine, expressions
from ..envelope import bad_request, not_found, ok
from ..query import tri_state
@ -848,6 +848,9 @@ def create_process(
approval_config=_clean_approval(body.approval_config or {}, DEFAULT_APPROVAL),
title_config=_clean_title_config(body.title_config or {}),
serial_config=_clean_serial_config(body.serial_config or {}),
# 建流程这一刻还没有环节清单,环节那一项不判(默认起手图里的环节 id 也还没生成)
terminate_config=_clean_terminate_config(
db, body.terminate_config or {}, None, None, body.latest_form or ""),
creator=user.person_id,
creator_name=user.display_name,
)
@ -962,6 +965,12 @@ def update_process(process_id: str, body: schemas.ProcessUpdateBody, db: Session
payload["serial_config"] = _clean_serial_config(
payload["serial_config"] or {}, row.serial_config or {}
)
if "terminate_config" in payload:
payload["terminate_config"] = _clean_terminate_config(
db, payload["terminate_config"] or {}, row.terminate_config or {},
[item.id for item in row.activities],
str(payload.get("latest_form") or row.latest_form or ""),
)
if "start_identity_list" in payload:
payload["start_identity_list"] = starters.clean_selectors(payload["start_identity_list"] or [])
if "category" in payload:
@ -1101,6 +1110,35 @@ def _clean_serial_config(payload: dict, base: dict | None = None) -> dict:
return numbering.clean_timing(body)
def _clean_terminate_config(
db: Session,
payload: dict,
base: dict | None = None,
activity_ids: list[str] | None = None,
form: str = "",
) -> dict:
"""归一化「终止」那一格:谁能终止、到什么时候为止、终止那一刻发什么写回。
分寸与 :func:`_clean_serial_config` 一样——读的时候宽容收敛,**写的时候严格**:
设计者亲手点了「走到部门主管之后不许发起人终止」而服务端悄悄存成「随时能终止」,
又是那种"界面说一套、跑起来做一套"最难查的账。环节 id 也在这儿验:它是每条流程
自己的主键,复制流程、恢复版本都会换掉它,指着一个已经不存在的环节等于这条规矩
永远不生效;写回那半当场点名三种病(模板被删、被停用、绑的是另一张表单),判据与
全库体检共用一份(``mapping.mount_code_problems``),``form`` 传这条流程的默认表单。
"""
body = dict(base or {})
body.update({key: value for key, value in dict(payload or {}).items()
if key in ("allowStarter", "until", "untilActivity", "untilHours", "writeback")})
problems = terminate_service.problems(body, activity_ids)
for problem in mapping.mount_code_problems(
db, terminate_service.writeback_mount(body), form=str(form or "")
):
problems.append(f"终止时要发的写回:{problem}")
if problems:
raise bad_request("终止配置有问题:" + ";".join(problems), reason="TERMINATE_CONFIG_INVALID")
return terminate_service.clean(body)
def _clean_open_approve(payload: dict, base: dict | None = None) -> dict:
"""归一化流程级「外部审批接口」默认档;写歪的键在这里就报出去。
@ -1326,6 +1364,14 @@ def save_design(process_id: str, body: schemas.ProcessDesignBody, db: Session =
process.title_config = _clean_title_config(body.title_config, process.title_config or {})
if body.serial_config is not None:
process.serial_config = _clean_serial_config(body.serial_config, process.serial_config or {})
if body.terminate_config is not None:
# 环节清单按**这一次一起交上来的**那份验:设计器里刚删掉的环节,保存这一刻就该喊,
# 不用等下一单走进终止才发现窗口指着一张已经不存在的环节。
process.terminate_config = _clean_terminate_config(
db, body.terminate_config, process.terminate_config or {},
[str(item.id or "") for item in body.activities if str(item.id or "")],
str(process.latest_form or ""),
)
if body.open_approve is not None:
process.open_approve = _clean_open_approve(body.open_approve, process.open_approve or {})
# 写回挂载(环节配置里的 writeback)也在这一次保存里验:模板被删了、补救路线不存在、
@ -1676,6 +1722,7 @@ def copy_process(
data_template=copy.deepcopy(source.data_template or {}),
title_config=copy.deepcopy(source.title_config or {}),
serial_config=copy.deepcopy(source.serial_config or {}),
terminate_config=copy.deepcopy(source.terminate_config or {}),
start_identity_list=list(source.start_identity_list or []),
manageable_identity_list=list(source.manageable_identity_list or []),
visible_identity_list=list(source.visible_identity_list or []),
@ -1720,6 +1767,14 @@ def copy_process(
if timing["at"] == numbering.TIMING_ACTIVITY and timing["activity"]:
timing["activity"] = mapping.get(timing["activity"], timing["activity"])
clone.serial_config = timing
# 「走到某环节之后不许发起人终止」指着的那一环同理:副本里环节换了 id,
# 不换过来这条窗口就指着一个不在副本图里的 id,等于副本上发起人随时能终止。
terminate_body = terminate_service.clean(clone.terminate_config or {})
if terminate_body["untilActivity"]:
terminate_body["untilActivity"] = mapping.get(
terminate_body["untilActivity"], terminate_body["untilActivity"]
)
clone.terminate_config = terminate_body
db.commit()
return ok(serializers.process(clone))

View File

@ -26,6 +26,7 @@ from ..deps import CurrentUser, current_user, require_permission
from ..envelope import bad_request, not_found, ok
from ..engine import engine
from ..service import autofill, fetch, mapping, outbox
from ..service import terminate as terminate_service
router = APIRouter(tags=["integration"])
@ -385,6 +386,18 @@ def audit(db: Session) -> list[dict]:
items.append({"kind": "template", "code": str(row.code or ""),
"name": str(row.name or row.code or ""), "process": "",
"problems": problems})
for process in db.scalars(select(models.Process).order_by(models.Process.name)):
# 流程那一格「终止时调用哪些回写模板」也扫一遍:终止不挂环节,L3 那轮扫不到它,
# 而模板被删 / 被停用恰恰是保存之后才发生的事(判据与保存流程那一道共用
# ``mapping.mount_code_problems``,两边不许各写一份)
mount = terminate_service.writeback_mount(process.terminate_config or {})
if mapping.mount_codes(mount):
problems = mapping.mount_code_problems(
db, mount, form=str(process.latest_form or ""))
if problems:
items.append({"kind": "terminate", "code": "",
"name": str(process.name or process.id),
"process": str(process.id or ""), "problems": problems})
for process in db.scalars(select(models.Process).order_by(models.Process.name)):
activities = list(db.scalars(
select(models.Activity).where(models.Activity.process == process.id)))
@ -488,12 +501,36 @@ def template_firing(code: str, db: Session = Depends(get_db), _: CurrentUser = D
"goBackVia": via_tokens,
"goBackViaText": mapping.goback_via_text(via_tokens) if via_tokens else "",
})
# 第三处绑定点:流程自己那一格「终止时调用哪些回写模板」。漏了它,配模板的人在这屏
# 看不见"这条流程终止时会发我",又得回流程设计器里回忆一遍(这一格存在的理由恰恰是
# 终态勾选管不到"只有这一条流程要发",见 docs/node-writeback-config.md §5.5.1)
terminate_mounts: list[dict] = []
for process in db.scalars(select(models.Process).order_by(models.Process.name)):
mount = terminate_service.writeback_mount(process.terminate_config or {})
if not mount:
continue
for index, block in enumerate(mapping.mount_blocks(mount)):
if code not in [name for name, _ in mapping.mount_entries(block)]:
continue
triggers = mapping.mount_triggers(block)
if mapping.TRIGGER_TERMINATE not in triggers:
continue
terminate_mounts.append({
"process": str(process.id or ""),
"processName": str(process.name or process.id or ""),
"triggers": triggers,
"triggerText": mapping.trigger_text(triggers),
# 多条规则时点名是第几条,与环节挂载那一屏同一措辞
"label": f"{process.name or process.id} · 终止"
+ (f" · 第 {index + 1} 条规则" if len(mapping.mount_blocks(mount)) > 1 else ""),
})
declared = mapping.declared_activity_of(row)
return ok({
"terminalEvents": list(mapping.terminal_events_of(row)),
# 旧写法:模板自己点名了一个环节。新的环节时机不再从这儿走,界面上标着"旧写法"给出入口
"declaredActivity": _activity_names(db, declared) if declared else None,
"mounts": mounts,
"terminateMounts": terminate_mounts,
})

View File

@ -16,7 +16,7 @@ from .. import models, parallel, permissions, schemas, serializers
from ..db import get_db
from ..deps import CurrentUser, actor_of, client_ip, current_user, require_permission
from ..service import autofill, completed as completed_service, flowmap, formruntime, numbering
from ..service import outbox, personref, starters, titles
from ..service import outbox, personref, starters, terminate as terminate_service, titles
from ..service import embed_session, external_check, gate, node_approve, org
from ..engine import definition as definition_module
from ..engine import engine
@ -251,7 +251,7 @@ def preview_work_title(
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
"""办理页的标题实时预览:审批人改字段时,告诉他提交后标题会变成哪一句。
"""办理页 / 干预面板的标题实时预览:改字段时,告诉他提交后标题会变成哪一句。
与发起页那只输入框不同,这一页的改动还没落库、标题也归引擎在提交时按
``refresh`` 开关重算,所以这里只**算给人看**,一个字都不写回单据
@ -261,8 +261,12 @@ def preview_work_title(
work = db.execute(select(models.Work).where(models.Work.job == job)).scalar_one_or_none()
if work is None:
raise not_found("单据不存在或已被删除")
# 只有在这张单上有事做的人看得见:手里有待办的、发起人本人、管理员
if not user.is_admin and work.creator != user.person_id and not db.execute(
# 只有在这张单上有事做的人看得见:手里有待办的、发起人本人、管理员;
# 再加上监控页动得了这张单的人——干预面板改表单时也要预告标题会换成哪一句,
# 可见范围与 /admin/work/{job}/data 用同一道数据范围筛。
if user.can("monitor:work"):
_ensure_in_scope(db, user, work.creator_identity)
elif work.creator != user.person_id and not db.execute(
select(models.Task.id).where(
models.Task.work == work.id, models.Task.identity == user.ref,
models.Task.status == "pending",
@ -527,6 +531,14 @@ def _job_response(db: Session, user: CurrentUser, job: str, row, *, running: boo
a.id: serializers_activity_brief(a, definition.approval, process=definition, lock=locks.get(a.id))
for a in definition.activities.values()
}
# 终止那颗钮给不给这个人看:管理员恒给;发起人除了"是自己发起的",还要过流程那一格
# 终止配置(整个关掉、或已经过了"什么时候为止"那条线)。判据只有一处
# (engine.terminate_blocker),界面显示与引擎放行说的必须是同一句话。
starter_blocker = ""
if running and not user.is_admin and row.creator == user.person_id:
# 只有发起人本人才需要知道"我为什么按不动":别人来看这张单,这一格留空,
# 也省掉一次没意义的判据查询(管理员恒能终止,同样不必问)。
starter_blocker = engine.terminate_blocker(db, row, definition, _actor(user))
return ok(
{
**serializers.work(row),
@ -566,7 +578,11 @@ def _job_response(db: Session, user: CurrentUser, job: str, row, *, running: boo
}
for r in definition.routes
],
"can_terminate": running and (user.is_admin or row.creator == user.person_id),
"can_terminate": running and (user.is_admin or (row.creator == user.person_id and not starter_blocker)),
# 挡下的那句原话:按钮不显示时,页面得有个地方说清"为什么不能终止"
"terminate_hint": starter_blocker,
"writeback": loaded["writeback"],
# 开始环节停在等提交的那一单(第三方审批:hold 建单):界面上要看得出
# 「这一单还没提交出去」,并且该谁按那颗钮、谁已经替他备好了表态。
@ -736,12 +752,17 @@ def terminate_job(
db: Session = Depends(get_db),
request: Request = None, # type: ignore[assignment]
) -> dict:
# 原因必填:终止把别人手上的待办直接抹掉,档案里只留一句系统兜底的「流程终止」,
# 事后谁也说不清是谁为什么撤了这张单(2026-11 那条报销单就是这么变成一笔糊涂账的)。
reason = str(body.opinion or "").strip()
if not reason:
raise bad_request("请先写一句终止原因:这句话会进审批记录,也会随通知发给被终止掉待办的人")
result = _retry_on_deadlock(
db,
lambda: engine.terminate(db, job=job, actor=_actor(user), opinion=body.opinion),
lambda: engine.terminate(db, job=job, actor=_actor(user), opinion=reason),
what="终止流程",
)
_log_operation(db, user, "terminate_job", job, f"终止流程:{body.opinion}", request)
_log_operation(db, user, "terminate_job", job, f"终止流程:{reason}", request)
db.commit()
return ok({"status": result.status})
@ -1039,9 +1060,29 @@ def list_created(
db, parts, offset=(page - 1) * page_size, limit=page_size, with_data=with_data
)
items = [serializers.work(row, with_data=with_data) for row in rows]
# 列表上那颗「终止」跟着流程那一格开关走:关了就整颗不摆,别让人点一次才知道不让。
# 窗口类判据(走到哪一环之后、过了多少小时)不在这里算——那要按每张单到过的环节现查,
# 一行一次往返为了一颗按钮不值当,那些留给详情页与引擎去判。
allowed = _starter_terminate_flags(db, rows)
for item, row in zip(items, rows):
item["terminate_allowed"] = bool(allowed.get(str(row.process or ""), True))
return ok(serializers.page(items, total, page, page_size))
def _starter_terminate_flags(db: Session, rows) -> dict[str, bool]:
"""这批单据各自那条流程开没开「发起人终止」:一页一条 SQL,按流程 id 去重回表。"""
ids = {str(getattr(row, "process", "") or "") for row in rows}
ids.discard("")
if not ids:
return {}
out: dict[str, bool] = {}
for process_id, config in db.execute(
select(models.Process.id, models.Process.terminate_config).where(models.Process.id.in_(ids))
).all():
out[str(process_id)] = terminate_service.allowed_by_config(terminate_service.clean(config or {}))
return out
def _created_clause(model, user, keyword, process, status, start_date, end_date):
"""「我发起的」的过滤条件,两张表、两种取法共用一份口径。

View File

@ -251,6 +251,10 @@ class ProcessDefinition:
#: service/node_approve.effective_config。详情页命中设计缓存时手上没有流程行,
#: 这一份是它唯一的来源,所以必须跟 ``approval`` / ``title`` 一起进缓存。
open_approve: dict = field(default_factory=dict)
#: 「终止」的流程级配置(谁能终止、到什么时候为止、终止那一刻发什么写回),
#: 见 models.Process.terminate_config 与 service/terminate.py。读它请走
#: ``terminate.config_of(definition)``,别直接信里面的键。
terminate: dict = field(default_factory=dict)
#: 这一份是不是**冻结定义**(单据发起那一刻的 :class:`models.ProcessSnapshot`)。
#: ``False`` = 现读的当前设计,行为与"在途单冻结设计"这套机制之前一字不差。
pinned: bool = False
@ -336,8 +340,9 @@ _PROCESS_FIELDS = ("id", "name", "alias", "category", "category_name", "latest_f
#: 后加的列:写的时候一起写,读的时候**缺了不算形状不对**。设计快照是不可变的、也没有
#: 重拍这一说(钉住的那个 id 就写在单据上),拿必需列去卡它,等于让这一列之前拍的所有
#: 快照整体作废、那些在途单从此跟着当前设计走——"改图不影响在途单"这条就默默没了。
#: 缺这一列按空默认档处理:环节上那份 ``openApprove`` 本来就在 ``config`` 里,冻得住。
_PROCESS_OPTIONAL_FIELDS = ("open_approve",)
#: 缺这一列按空默认档处理:环节上那份 ``openApprove`` 本来就在 ``config`` 里,冻得住;
#: ``terminate_config`` 同理——终止那格是后来加的,缺了就按"发起人随时能终止"跑。
_PROCESS_OPTIONAL_FIELDS = ("open_approve", "terminate_config")
_ACTIVITY_FIELDS = ("id", "type", "name", "alias", "description", "form", "config",
"x", "y", "order_number")
_ROUTE_FIELDS = ("id", "name", "alias", "from_activity", "to_activity", "decision",
@ -702,6 +707,7 @@ def build(
title=dict(getattr(process, "title_config", None) or {}),
serial=dict(getattr(process, "serial_config", None) or {}),
open_approve=dict(getattr(process, "open_approve", None) or {}),
terminate=dict(getattr(process, "terminate_config", None) or {}),
)
for row in activities:
definition.activities[row.id] = ActivityNode(

View File

@ -23,7 +23,8 @@ from sqlalchemy.orm import Session
from .. import models, readcache, storage
from ..service import (autofill, channels, dicts, events, external_check, fetch, formruntime,
gate, numbering, org, outbox, personref, quota, threshold, titles)
gate, numbering, org, outbox, personref, quota, terminate as terminate_service,
threshold, titles)
from . import definition as definition_module
from . import expressions, lookahead, tickets
from .definition import (
@ -234,6 +235,27 @@ def _backfill_serial(db: Session, work: models.Work) -> None:
db.execute(update(model).where(model.work == work.id).values(serial=serial))
def _refresh_title(
db: Session,
work: models.Work,
definition: ProcessDefinition,
*,
actor: Actor | None = None,
fields: list[dict] | None = None,
force: bool = False,
) -> bool:
"""表单动过之后把标题按同一规则算回来,在途的待办与待阅一起改名;返回标题是否真的换了。
改表单的三条路都走这一句:审批人办单(:func:`execute_task`)、晚排号补标题
(:func:`issue_serial`)、管理员修正表单(:func:`fix_data`)。列表和站内信读的是
待办 / 待阅各行自己那一份 ``title``,只换 ``work.title`` 就是「详情页改了名字、
列表还写着老那一句」,所以两处必须一起改,口径见 :func:`app.service.titles.refresh`。
"""
if not titles.refresh(db, work, definition, actor=actor, fields=fields, force=force):
return False
titles.sync_pending_titles(db, work.id, work.title)
return True
def issue_serial(
db: Session,
work: models.Work,
@ -262,15 +284,7 @@ def issue_serial(
work.serial = next_serial(db, work.process, numbering.serial_rule_of(shown))
_sync_serial_fields(work, shown)
_backfill_serial(db, work)
if titles.refresh(db, work, definition, actor=actor, fields=shown, force=True):
titles.sync_task_titles(
db.execute(
select(models.Task).where(
models.Task.work == work.id, models.Task.status == "pending"
)
).scalars().all(),
work.title,
)
_refresh_title(db, work, definition, actor=actor, fields=shown, force=True)
_log_serial(db, work, definition, actor)
db.flush()
return True
@ -1716,6 +1730,10 @@ LOG_SERIAL = "serial"
#: 外部核验闸门**放行**时旁挂的那一句(人工放行 / 带病放行 / 部分通过)。
#: 挡住的那一次不会有这条:EngineError 一抛整笔事务回滚,留痕写了也不存在。
LOG_GATE_PASS = "gatePass"
#: 终止流程旁挂的那一句(:func:`terminate`)。终止本身**不写流转留痕**——它不是一步流转,
#: 也没有"到达"哪个环节,从前一张单被谁终止、写了什么原因,审批记录里一个字都查不到,
#: 只能去翻操作日志。这条留痕把操作人(``from_identity_name``)与原因留在单子上。
LOG_TERMINATE = "terminate"
#: 干预类站内信的事件名。不进 ``channels.EVENTS``:挂起 / 改道这种动作只在站内信里看,
#: 没必要跟着「新的待办」一起往邮箱和群里刷。
NOTIFY_CONTROL = "control"
@ -2521,17 +2539,8 @@ def execute_task(
# 本环节改了标题引用的字段就按同一规则重算:标题开了自动刷新时,
# 「张三的请假申请」补完事由该变成「张三的请假申请(出差上海)」。
# 待办列表和站内信读的是 task.title,跟着一起改,否则两边说的不是同一件事。
# 表单里有「流程标题」字段时,办理人改了这个字段就等于改了标题,这里一并接住。
if titles.refresh(db, work, definition, actor=actor, fields=activity_fields):
titles.sync_task_titles(
db.execute(
select(models.Task).where(
models.Task.work == work.id, models.Task.status == "pending"
)
).scalars().all(),
work.title,
)
_refresh_title(db, work, definition, actor=actor, fields=activity_fields)
route = _resolve_route(definition, activity, route_name, work, data, db=db, actor=actor)
if route is None:
@ -2951,7 +2960,14 @@ def _complete_task(
now: datetime,
processing_type: str,
form_changes: list[dict] | None = None,
operator: Actor | None = None,
) -> models.TaskCompleted:
# 替这一步收尾的人:终止把还挂着的待办强行结掉时,行仍旧记在持有人名下(他的已办里
# 得看得见这张单),但要把"是谁按的终止"留在行上——不然审批记录读起来就是
# 「部门主管自己终止了这张单」,而那位主管连待办都没打开过。本人办的那些留空。
is_holder = operator is None or str(operator.ref or "") == str(task.identity or "")
operator_ref = "" if is_holder else str(operator.ref or "")
operator_name = "" if is_holder else str(operator.person_name or "")
completed = models.TaskCompleted(
task=task.id,
job=task.job,
@ -2992,6 +3008,8 @@ def _complete_task(
processing_type=processing_type,
act=task.act,
label=task.label,
operator=operator_ref,
operator_name=operator_name,
latest=True,
press_count=task.press_count,
press_time=task.press_time,
@ -3673,7 +3691,8 @@ def reset_task(
child_job = str(token.get("embed_job") or "")
if child_job:
try:
terminate(db, job=child_job, actor=actor, opinion="父流程已撤回到上游环节,子流程一并终止")
terminate(db, job=child_job, actor=actor, opinion="父流程已撤回到上游环节,子流程一并终止",
enforce_starter_config=False)
except EngineError:
logger.exception("撤回时未能终止嵌入子流程 %s", child_job)
drop_ids = {t.get("id") for t in dropped}
@ -3761,8 +3780,80 @@ def press(db: Session, *, task_id: str, actor: Actor, opinion: str = "") -> mode
return task
def terminate(db: Session, *, job: str, actor: Actor, opinion: str = "") -> StepResult:
"""终止/作废流程."""
def terminate_facts(db: Session, work: models.Work) -> dict:
"""「现在还能不能终止」要看的那三份事实:到过哪些环节、别人办过没有、发起多久了。
``reached`` 取"到过"而不是"正停在哪一环":留痕里的到达记录 + 在路上的 token + 单据
游标三处并起来,单子从指定环节流走之后照样算"过线了"。
``handled_by_others`` 只认**别人办完过一步**(``processing_type=normal``):转办与自动结掉
都不算有人真表过态,而发起人自己填的那一步也不算——那张单还没落到任何人手上。
"""
reached: set[str] = set(
db.execute(select(models.WorkLog.arrived_activity).where(models.WorkLog.work == work.id))
.scalars()
)
reached.update(str(token.get("activity") or "") for token in (work.tokens or []))
reached.add(str(work.activity or ""))
handled = db.execute(
select(func.count(models.TaskCompleted.id)).where(
models.TaskCompleted.work == work.id,
models.TaskCompleted.processing_type == "normal",
models.TaskCompleted.identity != work.creator_identity,
)
).scalar() or 0
started = work.start_time or work.create_time or datetime.now()
return {
"reached": {item for item in reached if item},
"handled_by_others": bool(handled),
"elapsed_hours": max(0.0, (datetime.now() - started).total_seconds() / 3600.0),
}
def terminate_blocker(db: Session, work: models.Work, definition: ProcessDefinition, actor: Actor) -> str:
"""发起人在这一刻终止得动吗;回一句为什么动不了,能终止回空串。
判据只有一处(:func:`app.service.terminate.starter_blocker`),界面上那句提示与
引擎挡下时抛的那一句同源。**管理员不在约束范围内**:监控里的终止是干预手段,
流程那一格管的是"发起人能不能收拾自己已经交出去的单"。
"""
if actor.is_admin:
return ""
config = terminate_service.config_of(definition)
if not terminate_service.allowed_by_config(config):
# 钮都关了,三份事实不必再问库:这一句就是全部答案
return terminate_service.starter_blocker(config)
# 环节上那一格是硬闸:单据正停着的那一环关掉了终止钮,发起人这会儿就按不动
# (与「退回」「撤回」那两颗钮同一个开关家族,见 serializers_activity_brief)
current = definition.activity(str(work.activity or ""))
if current is not None and not bool((current.config or {}).get("allowTerminate", True)):
return f"「{current.name}」这一环关掉了终止,发起人不能再终止这张单;请联系流程管理员。"
if config["until"] == terminate_service.UNTIL_ALWAYS:
return "" # 没设窗口:一次库都不问
node = definition.activity(str(config.get("untilActivity") or ""))
facts = terminate_facts(db, work)
return terminate_service.starter_blocker(
config,
reached=facts["reached"],
handled_by_others=facts["handled_by_others"],
elapsed_hours=facts["elapsed_hours"],
activity_name=node.name if node is not None else "",
)
def terminate(db: Session, *, job: str, actor: Actor, opinion: str = "",
enforce_starter_config: bool = True) -> StepResult:
"""终止/作废流程.
终止是**整张单**的动作,不是当前那一环的表态:还挂着的待办会被强行结掉,那些行留在
原持有人名下(他的已办里要看得见这张单),但 ``operator`` 那一列写的是按终止的人,
并旁挂一条 :data:`LOG_TERMINATE` 留痕把操作人与原因落在单子上。
发起人这一路还要过流程自己那一格终止配置(谁能终止、到什么时候为止,
见 :mod:`app.service.terminate`);管理员与开放接口那两路只受"是不是发起人/管理员"约束。
``enforce_starter_config=False`` 留给**引擎替父单收尾**那两处级联(撤回时收回自动流转
出去的嵌入子流程、父单归档时带走还在跑的子单):那一格管的是"人能不能收拾自己交出去
的单",而级联是父单那一步已经合法走完之后的连带清理,按不住、也不该按不住——真挡住了
只会留下一张父单已归档、子单还挂着待办的孤儿单,而那两处又是 ``except EngineError``
只记日志的,失败悄无声息。
"""
work = db.execute(select(models.Work).where(models.Work.job == job)).scalar_one_or_none()
if work is None:
raise EngineError("单据不存在或已被删除")
@ -3771,18 +3862,44 @@ def terminate(db: Session, *, job: str, actor: Actor, opinion: str = "") -> Step
if not (actor.is_admin or work.creator == actor.person_id):
raise EngineError("只有发起人或管理员可以终止流程")
definition = definition_module.for_work(db, work)
blocker = terminate_blocker(db, work, definition, actor) if enforce_starter_config else ""
if blocker:
raise EngineError(blocker)
now = datetime.now()
reason = (opinion or "").strip() or "流程终止"
pending = db.execute(select(models.Task).where(models.Task.work == work.id)).scalars().all()
# 待办一消失就得喊人:不然对方手上那条「等待您在 XX 环节处理」永远挂着,
# 点进去一张已归档的单,谁都不知道这张单还要不要办。
handlers = [item for item in dict.fromkeys(str(task.identity or "") for task in pending)
if item and item != str(actor.ref or "")]
for task in pending:
_complete_task(
db, task, actor,
definition_module.RouteNode(id="terminate", name="终止", alias="终止", from_activity=task.activity, to_activity=""),
opinion or "流程终止", "", now, "terminate",
reason, "", now, "terminate", operator=actor,
)
return _finish_work(
db, work, definition, status="terminated", result=StepResult(), actor=actor,
opinion=opinion or "流程终止", activity=None,
_event_log(
db, work, _cursor_activity(work, definition), actor,
f"{actor.person_name} 终止了流程:{reason}", LOG_TERMINATE,
)
# 归档那一刻 ``oa_work`` 整行搬走并删掉,通知要的这几样先抄下来
work_id, work_job, work_process, work_title = work.id, work.job, work.process, work.title
result = _finish_work(
db, work, definition, status="terminated", result=StepResult(), actor=actor,
opinion=reason, activity=None,
)
if handlers:
notify(
db, handlers,
type_=NOTIFY_CONTROL,
title=f"待办已终止:{work_title}",
body=f"{actor.person_name} 终止了《{work_title}》,你手上那条待办不再需要办理。原因:{reason}",
job=work_job,
work=work_id,
process=work_process,
sender=actor.person_name,
)
return result
#: 删除未发起的单时一起清掉的运行表。这张单从没进过任何人的办理,挂在它身上的只有
@ -4237,6 +4354,11 @@ def fix_data(db: Session, *, job: str, actor: Actor, data: dict | None, opinion:
与审批人办单时改表单同一个口径(都只收页面交上来的那几项、都记下改了什么),
差别只在这里没有「环节字段权限」可依据,所以按表单字段整份比差异、
系统留痕(下划线开头那些)照旧由服务端自己写,页面盖不掉。
改完也要把标题对齐(:func:`_refresh_title`):表单里那格「流程标题」被管理员改了、
或者改的字段正被标题规则引用,``work.title`` 与在途的待办 / 待阅都跟着换一句——
这一层没做就是「面板里明明改好了,列表里还写着老那一句」。顺带把这一层修好之前留下的
歪账治好:那一格与 ``work.title`` 本来就对不上时,哪怕这次一个字没改也认下来,
不然老单子只能靠再改点别的才能把名字对齐。
"""
work = _running_work(db, job)
definition = _definition_of(db, work)
@ -4247,12 +4369,24 @@ def fix_data(db: Session, *, job: str, actor: Actor, data: dict | None, opinion:
if not incoming:
raise EngineError("没有要修正的表单内容")
changes = form_change_notes(fields, before, {**before, **incoming}, incoming)
if not changes:
raise EngineError("表单内容没有变化")
work.data = {**before, **incoming}
# 标题跟着表单走:那一格归管理员改的就是标题,动了规则引用的字段也算改标题。
# 环节挂的是另一张表单、标题格还留在发起那张上时(面板上摆出来的可能就是发起表单),
# 把发起表单的字段一起摊进来认一次,认法同 titles.refresh 找落点时的那道回退。
shown = fields
if titles.form_title_field(fields) is None:
shown = [*fields, *titles.start_fields(db, work, definition)]
title_before = str(work.title or "")
renamed = _refresh_title(db, work, definition, actor=actor, fields=shown)
# 「没有变化」要等标题对齐之后再判:那一格与标题本来就对不上的老单子,
# 这次交上来的值跟库里一模一样,仍然有名字要对齐这一件事可做。
if not changes and not renamed:
raise EngineError("表单内容没有变化")
summary = ";".join(f"{item['label']}:{item['before']} → {item['after']}" for item in changes[:8])
if len(changes) > 8:
summary += f";等 {len(changes)} 处"
if not changes and renamed:
summary = f"标题:{title_before} → {work.title}"
note = f"{(opinion or '').strip() or '管理员修正表单数据'}({summary})"
_event_log(db, work, _cursor_activity(work, definition), actor, note[:1000], LOG_DATA_FIX)
notify(
@ -4953,6 +5087,13 @@ def _finish_work(
activity_name=getattr(work, "activity_name", "") or "",
actor_name=getattr(actor, "person_name", "") or "系统")
outbox.enqueue_event(db, work, status, actor=actor)
# 终止还有流程自己那一格:终止不是画布上的环节,挂不到任何一环上,
# 「这一条流程被终止时另外通知一声」只能配在流程上(service/terminate.py)。
if status == "terminated":
outbox.enqueue_terminate(
db, work, terminate_service.writeback_mount(terminate_service.config_of(definition)),
actor=actor,
)
# 终止/作废还要处理"上游已经有一张凭证了":配了冲销模板就自动发反向消息,
# 没配就只在原消息上挂一个人工待处理标记,机器不猜该不该作废(§6)
outbox.handle_reversal(db, work, status, actor=actor)
@ -5040,7 +5181,9 @@ def _finish_work(
cascade_actor = actor or owner
for orphan in embed_children:
try:
terminate(db, job=orphan, actor=cascade_actor, opinion=f"父流程已{('办结' if status == 'completed' else '终止')},子流程一并终止")
terminate(db, job=orphan, actor=cascade_actor,
opinion=f"父流程已{('办结' if status == 'completed' else '终止')},子流程一并终止",
enforce_starter_config=False)
except EngineError:
logger.exception("嵌入子流程 %s 未能随父单收尾", orphan)
return result

View File

@ -1530,6 +1530,13 @@ class Process(Base, TimestampMixin):
#: 优先于这里(口径与 ``approval_config`` 一致)。空 dict = 没配过,任何环节都关着。
#: 见 service/node_approve.py 与 docs/node-open-approve-design.md。
open_approve: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
#: 「终止」这一动作的流程级配置。空 dict = 没配过 = 老行为(发起人随时能终止、
#: 终止那一刻不再额外发写回)。每一格的读法只在 :mod:`app.service.terminate` 一处:
#: ``allowStarter`` 发起人还能不能终止(关掉:界面上不出现那颗钮,引擎也挡),
#: ``until`` / ``untilActivity`` / ``untilHours`` 说的是**什么时候之后**不再允许他终止,
#: ``writeback`` 是终止那一刻要调用的回写模板挂载(形状同环节挂载,时刻固定 terminate)。
#: 管理员不受这套约束:他手上的终止是流程监控里的干预手段,不是发起人在收拾自己的单。
terminate_config: Mapped[JsonDict] = mapped_column(JsonDict, default=dict, nullable=False)
open_create: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
icon: Mapped[str] = mapped_column(String(255), default="", nullable=False)
@ -1931,6 +1938,11 @@ class TaskCompleted(Base, TimestampMixin):
processing_type: Mapped[str] = mapped_column(String(32), default="normal", nullable=False)
act: Mapped[str] = mapped_column(String(32), default="create", nullable=False)
label: Mapped[str] = mapped_column(String(255), default="", nullable=False)
#: 替这一步收尾的人:只在**不是本人表态**的那些记录上有值(目前只有终止——引擎把当时
#: 还挂着的待办强行结掉,``identity`` 仍是那位没来得及表态的处理人,不写清楚就成了
#: 「部门主管自己终止了这张单」)。空 = 本人办的,界面上不多嘴。见 engine.terminate。
operator: Mapped[str] = mapped_column(String(512), default="", nullable=False)
operator_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
latest: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
retract_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
press_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

View File

@ -429,6 +429,8 @@ class ProcessBody(CamelModel):
title_config: dict[str, Any] = Field(default_factory=dict)
#: 编号生成时机,见 service/numbering.py 的 timing 一节。
serial_config: dict[str, Any] = Field(default_factory=dict)
#: 「终止」的流程级配置,见 service/terminate.py。
terminate_config: dict[str, Any] = Field(default_factory=dict)
#: 建流程这一刻就定下的默认表单。给了就认它(环节全部沿用,不再各点一遍),
#: 没给则由 ``_add_default_design`` 现建一张只有「申请事由」的起手表单。
latest_form: str = ""
@ -449,6 +451,9 @@ class ProcessDesignBody(CamelModel):
#: 编号生成时机;不传就当没改。指哪个环节就写环节的 id,
#: 保存那一刻会对着这一次一起提交的环节清单验它还在不在(见 api/design.py)。
serial_config: dict[str, Any] | None = None
#: 「终止」的流程级配置(谁能终止、到什么时候为止、终止那一刻发什么写回);
#: 不传就当没改。指哪个环节就写环节的 id,保存那一刻同样验它还在不在。
terminate_config: dict[str, Any] | None = None
#: 环节外部审批接口的流程级默认档;不传就当没改。
#: 环节上 ``config.openApprove`` 显式配置的键优先于这里(口径与 approval_config 一致)。
open_approve: dict[str, Any] | None = None
@ -554,6 +559,8 @@ class ProcessUpdateBody(CamelModel):
title_config: dict[str, Any] | None = None
#: 编号生成时机;不传就当没改,见 service/numbering.py。
serial_config: dict[str, Any] | None = None
#: 「终止」的流程级配置;不传就当没改,见 service/terminate.py。
terminate_config: dict[str, Any] | None = None
# --------------------------- dicts ---------------------------

View File

@ -241,6 +241,7 @@ def process(row: models.Process, *, with_definition: bool = True, **extra: Any)
"title_config": (getattr(row, "title_config", None) or {}) if with_definition else {},
"serial_config": (getattr(row, "serial_config", None) or {}) if with_definition else {},
"open_approve": (getattr(row, "open_approve", None) or {}) if with_definition else {},
"terminate_config": (getattr(row, "terminate_config", None) or {}) if with_definition else {},
"open_create": row.open_create,
"order_number": row.order_number,
"icon": row.icon,
@ -262,6 +263,7 @@ PROCESS_DEFINITION_COLUMNS = (
models.Process.approval_config,
models.Process.title_config,
models.Process.serial_config,
models.Process.terminate_config,
models.Process.query_fields,
)
@ -409,6 +411,9 @@ def task_completed(row: models.TaskCompleted) -> dict:
"duration": row.duration,
"processing_type": row.processing_type,
"label": row.label,
# 替这一步收尾的人(目前只有终止会写):界面拿它说明"这一行不是本人表的面"
"operator": row.operator or "",
"operator_name": row.operator_name or "",
"latest": row.latest,
"retract_time": dt(row.retract_time),
"view_time": dt(row.view_time),

View File

@ -53,12 +53,17 @@ TRIGGER_LEAVE = "leave"
TRIGGER_GOBACK = "goBack"
TRIGGER_RECALL = "recall"
TRIGGERS = (TRIGGER_ARRIVE, TRIGGER_LEAVE, TRIGGER_GOBACK, TRIGGER_RECALL)
#: 流程级「终止那一刻」的挂载时刻。**不在** :data:`TRIGGERS` 里:终止不是画布上的环节,
#: 挂不到任何一环上,它挂在流程自己身上(``oa_process.terminate_config.writeback``,
#: 见 :mod:`app.service.terminate`)。形状仍用这一层的挂载读法,只多这一个时刻取值。
TRIGGER_TERMINATE = "terminate"
#: 触发时刻的中文说法:体检文案、``{action.phase_name}``、发件箱那一列共用一份
TRIGGER_LABELS = {
TRIGGER_ARRIVE: "到达本环节时",
TRIGGER_LEAVE: "本环节审批通过后",
TRIGGER_GOBACK: "本环节被退回时",
TRIGGER_RECALL: "本环节被撤回时",
TRIGGER_TERMINATE: "流程终止时",
}
#: 退回 / 撤回这两个时刻要在幂等键里补一段,才和「通过后」那条分得开。``arrive`` /
#: ``leave`` 那一段**留空**:存量报文的幂等键一个字节都不变,升级之后旧单第二次命中仍旧
@ -72,6 +77,8 @@ TRIGGER_ALIASES = {
"leave": TRIGGER_LEAVE,
"goback": TRIGGER_GOBACK, "go_back": TRIGGER_GOBACK, "back": TRIGGER_GOBACK,
"recall": TRIGGER_RECALL, "retract": TRIGGER_RECALL, "reset": TRIGGER_RECALL,
# 流程级终止那一格:导出件与手改 JSON 里常见 terminated / termiate 之外的叫法就这两个
"terminate": TRIGGER_TERMINATE, "terminated": TRIGGER_TERMINATE,
}
#: 每个时刻能被哪些环节类型触发。配在这个环节根本没有的时刻 = 一条都不发的死配置,
#: 界面上不给选、保存流程时挡(与 :data:`ONE_WAY_TRIGGER` 同一条原则)。
@ -730,11 +737,46 @@ def mount_codes(mount: dict) -> list[str]:
return [code for code, _ in mount_all_entries(mount)]
def mount_entry_conditions(mount: dict) -> dict[str, dict]:
"""``编码 -> 这一格的条件``;没配条件的编码不在里面。"""
return {code: condition for code, condition in mount_entries(mount) if condition}
def mount_code_problems(db: Session, mount: dict, *, at: str = "", form: str = "") -> list[str]:
"""**流程级**挂载(``oa_process.terminate_config.writeback``)点名的模板还发得出吗。
环节挂载那一份有 :func:`mount_problems` 逐块体检(要判时机、落点、按钮开没开那一堆);
流程这一格只有一条规则、时刻固定是 ``terminate``,犯不着把那套环节判据搬过来,
但判的是同三样病,措辞也同一把尺子:模板被删了、被停用了、绑的是另一张表单——
那一刻都是一条都不发,而且不报错(``outbox.enqueue_terminate`` 逐条认这三道)。
保存流程(``api/design.py``)与全库体检(``api/integrations.py::audit``)**共用这一句**:
保存时只验得着"这一次保存的那一条",而模板是后来才被删掉、被停用的,只有回头扫才看得见。
``at`` 是措辞前缀,体检报告用它说清病在哪一条流程;``form`` 给这条流程的默认表单,
给了才判"绑的是另一张表单"那一条(新建流程那一刻还没有表单,就不判)。
"""
codes = mount_codes(mount) if mount else []
if not codes:
return []
rows = db.execute(
select(models.Integration).where(models.Integration.code.in_(codes))
).scalars().all()
by_code = {str(row.code or ""): row for row in rows}
out: list[str] = []
for code in codes:
template = by_code.get(code)
if template is None:
out.append(f"{at}编码 {code} 已经没有对应的写回模板了,终止那一刻不会发出去")
continue
name = str(template.name or code)
if not template.enabled:
out.append(f"{at}点名的写回模板「{name}」已经停用,终止那一刻什么都不会发")
if template.biz_form and form and template.biz_form != form:
out.append(f"{at}要发的模板「{name}」绑的是另一张表单,这条流程的单子终止时不会发它")
return out
def mount_entry_fields(block: dict) -> dict[str, list[str]]:
"""挂载里每个模板在这一格勾的「要发的字段」:``编码 -> [目标字段...]``。

View File

@ -592,6 +592,60 @@ def enqueue_node(
return out
def enqueue_terminate(
db: Session, work, mount: dict, *, actor=None
) -> list[models.OutboundMessage]:
"""流程终止那一刻:按**流程上那一格挂载**发一批写回。
三条终态的模板(``trigger_events``)按绑定表单自动找齐,管的是"这张表单的单据进终态
就要发";而"这一条流程被终止时另外通知一声"没地方说——终止不是画布上的环节,挂不到
任何一环上,同表单的另一条流程又不该跟着发。所以流程自己留一格(
``oa_process.terminate_config.writeback``,口径见 :mod:`app.service.terminate`),
由 :func:`app.engine.engine._finish_work` 在归档之前调这里,与终止同一事务。
幂等键里带 ``event_key=terminate`` 这一段,与「模板自己勾了终止」那条(``event_key``
为空)天然分开:同一个模板两处都配就会各发一条,界面与保存时都会提醒,不在这儿替人猜。
"""
if not mount:
return []
plan = mount_plan(mount, mapping.TRIGGER_TERMINATE)
codes = [code for block in mapping.mount_blocks(mount)
for code, _ in mapping.mount_entries(block)
if mapping.TRIGGER_TERMINATE in mount_triggers(block)]
if not codes:
return []
form = str(getattr(work, "form", "") or "")
out: list[models.OutboundMessage] = []
for integration in templates_of_codes(db, codes):
code = str(integration.code or "")
# 停用的模板不发:与模板自己声明终态那一路(``enabled_templates`` 只捞启用的)同口径,
# 也是设计器那一格当场说好的话——「已停用,终止那一刻不会发出去」
if not integration.enabled:
continue
holder = plan.get(code)
if holder is None:
continue
block, entry_when, entry_fields = holder
# 与环节挂载同一道闸门:整批条件、这一格的条件、模板自己那份「哪些单才发」,都过才发
if not (condition_passes(block.get("when"), work) and condition_passes(entry_when, work)):
continue
if integration.biz_form and integration.biz_form != form:
continue
if not sendable(integration, work):
continue
row = enqueue(
db, integration, work,
event=models.Integration.EVENT_TERMINATED, event_key=mapping.TRIGGER_TERMINATE,
actor=actor,
on_failure=mapping.mount_failure_policy(block),
only_fields=entry_fields or None,
phase=mapping.TRIGGER_TERMINATE,
action={"name": "终止", "decision": "terminate", "phase_name": mapping.TRIGGER_LABELS[mapping.TRIGGER_TERMINATE]},
)
if row is not None:
out.append(row)
return out
# ---------------------------------------------------------------------------
# 投递
# ---------------------------------------------------------------------------

View File

@ -0,0 +1,192 @@
"""「终止」这件事的流程级规矩:谁能终止、到什么时候为止、终止那一刻再发点什么。
背景是一条真实的单子(2026-11-04):报销单已经走到「部门主管」,主管一次都没打开过待办,
发起人自己把整张单终止了,第二天来问"部门主管为什么给我终止了"。终止这个动作在这套引擎里
一直是**谁都能随时按**——只要你是发起人,单子哪怕已经跑到最后一环也照样能按;按下去之后
既没有原因,也不告诉任何人,连上游业务系统都不知道。界面与配置都没有一处能说一句"这一条
流程不许这么干"。这里把那三句话补上,存在 ``oa_process.terminate_config``:
{"allowStarter": false} # 发起人的终止钮整个关掉
{"allowStarter": true, "until": "notHandled"} # 一旦有人办过就不许他终止
{"allowStarter": true, "until": "beforeActivity", "untilActivity": "cr_dept"}
# 走到「部门主管」(含)之后不许
{"allowStarter": true, "until": "withinHours", "untilHours": 24}
# 发起 24 小时之后不许
{"writeback": {"trigger": "terminate", "integrations": ["reimb_chct"]}}
# 终止那一刻调用哪些回写模板
三条口径要提前说死,免得日后当成 bug:
1. **只管发起人,不管管理员**。管理员在流程监控里的终止是干预手段(单子办错了要收尾),
和发起人收拾自己那张单是两件事;``admin`` 与开放接口那两条路照旧通。
2. **关掉就是界面不出现 + 引擎也挡**。只藏按钮不挡接口,等于给了一个能绕过规矩的口子;
只挡接口不藏按钮,用户就要点一次才知道不让。两边读的都是这里这一个判据。
3. ``until`` 是单选,不是可以叠的清单。四种窗口各有各的用处,叠在一起解释成本比收益高:
「走到某环节之后」与「超过 N 小时之后」都想要,就选更严格的那一条写清楚,
真要组合等有人提再说,别先造一个没人会配的开关矩阵。
写回那半(``writeback``)为什么挂在流程上而不是模板上:三条终态(办结 / 终止 / 作废)
的模板按**绑定表单**自动找齐,同一张报销表单挂了两条流程时,"终止时要通知上游"这件事
没法只给其中一条流程配;而终止又不是画布上的一个环节,挂不到环节上。所以流程自己留一格。
形状与环节挂载完全一致(``service/mapping.py`` 那一套读法),只是时刻固定是 ``terminate``。
"""
from __future__ import annotations
from typing import Any, Iterable
#: 「什么时候之前还允许发起人终止」的四种窗口。默认 ``always``:与这套配置存在之前的
#: 行为一字不差,老流程一条都不用迁移。
UNTIL_ALWAYS = "always"
#: 别人(不含发起人自己)在这张单上办完过一步之后就不许了。发起人自己填的那一步不算——
#: 那张单还没落到任何人手上,此时终止与撤回没多大分别。
UNTIL_NOT_HANDLED = "notHandled"
#: 走到指定环节(**含**该环节)之后不许。判据是"到过",不是"还停在那儿":
#: 单子从部门主管流走了,再让发起人终止,前面那位主管的表态就白做了。
UNTIL_BEFORE_ACTIVITY = "beforeActivity"
#: 发起之后过了 N 小时不许。报销单隔夜就没人再动,这类"第二天想起来才反悔"最该挡。
UNTIL_WITHIN_HOURS = "withinHours"
UNTILS = (UNTIL_ALWAYS, UNTIL_NOT_HANDLED, UNTIL_BEFORE_ACTIVITY, UNTIL_WITHIN_HOURS)
#: 小时档的取值范围:下限挡"配了个 0 结果等于从不允许"这种手滑,上限是整整一年。
HOURS_MIN = 1
HOURS_MAX = 24 * 365
#: 环节标识的长度上限,与库里那些 id 列同宽
ACTIVITY_ID_MAX = 32
#: 界面与提示共用的中文说法(后端要把挡下的理由说给人听,不能让界面自己猜)
UNTIL_LABELS = {
UNTIL_ALWAYS: "随时都能终止",
UNTIL_NOT_HANDLED: "有人办理之后就不能终止",
UNTIL_BEFORE_ACTIVITY: "走到指定环节之后就不能终止",
UNTIL_WITHIN_HOURS: "超过限定小时数之后就不能终止",
}
def _text(value: object, limit: int = 512) -> str:
return str(value if value is not None else "").strip()[:limit]
def _int(value: object, default: int = 0) -> int:
try:
return int(float(str(value if value is not None else "").strip() or default))
except (TypeError, ValueError):
return default
def clean(raw: object) -> dict[str, Any]:
"""把递来的那份配置收成干净形状:认不出的回到默认口径,不报错。
宽容只用在**读**:这一份是随流程定义存下来的 JSON,老数据、接口写的、手改库的都可能
撞上来,取值时宁可退回默认口径,也不该因为一句写歪的窗口把整条流程的终止都卡死。
写的时候严格,走 :func:`problems`。
"""
body = raw if isinstance(raw, dict) else {}
until = _text(body.get("until"), 32)
activity = _text(body.get("untilActivity") or body.get("until_activity"), ACTIVITY_ID_MAX)
hours = _int(body.get("untilHours") or body.get("until_hours"), 0)
writeback = body.get("writeback")
return {
# 缺键 = 没配过 = 允许,与这套配置存在之前一致
"allowStarter": body.get("allowStarter") is not False,
"until": until if until in UNTILS else UNTIL_ALWAYS,
# 只有环节档才留着环节 id:窗口换掉之后不留一条"看起来还指着某环节"的孤儿值
"untilActivity": activity if until == UNTIL_BEFORE_ACTIVITY else "",
"untilHours": hours if until == UNTIL_WITHIN_HOURS and hours >= HOURS_MIN else 0,
"writeback": writeback if isinstance(writeback, dict) else {},
}
def config_of(source: object) -> dict[str, Any]:
"""从流程行 / 流程定义上把配置读出来,缺啥补啥。
引擎传的是 :class:`~app.engine.definition.ProcessDefinition`(``.terminate``),
设计器与接口传的是 ``models.Process``(``.terminate_config``),一处兼容掉,
口径同 :func:`app.service.numbering.timing_of`。
"""
return clean(
getattr(source, "terminate", None) or getattr(source, "terminate_config", None) or {}
)
def problems(raw: object, activity_ids: Iterable[str] | None = None) -> list[str]:
"""保存流程时的把关:窗口写歪、说要按环节挡却没选环节,当场说清楚。
与 :func:`app.service.numbering.timing_problems` 同一个分寸——读的时候宽容收敛,
写的时候严格,免得"存进去是走到部门主管之后不让终止、跑起来却是随时能终止"。
``activity_ids`` 给了就把环节也验一遍:环节 id 是每条流程自己的主键,复制流程、
恢复版本都会换掉它,指着一条已经不存在的环节等于这条规矩永远不生效。
传 ``None`` 表示"这会儿还没定环节清单"(新建流程那一刻),这一项就不判。
"""
if raw is None or raw == {} or raw == "":
return []
if not isinstance(raw, dict):
return ["终止配置的格式不对,应当是一个对象"]
out: list[str] = []
until = _text(raw.get("until"), 32)
if until and until not in UNTILS:
out.append(f"终止窗口不支持:{until}")
activity = _text(raw.get("untilActivity") or raw.get("until_activity"), ACTIVITY_ID_MAX)
if until == UNTIL_BEFORE_ACTIVITY and not activity:
out.append("选了「走到指定环节之后不能终止」,得指定是哪个环节")
if activity and activity_ids is not None and activity not in set(activity_ids):
out.append(f"终止窗口指着的那个环节已经不在流程里了:{activity}")
hours_raw = raw.get("untilHours") if raw.get("untilHours") is not None else raw.get("until_hours")
if until == UNTIL_WITHIN_HOURS:
hours = _int(hours_raw, 0)
if hours < HOURS_MIN:
out.append(f"限定小时数至少 {HOURS_MIN} 小时,填 0 等于从不允许发起人终止")
elif hours > HOURS_MAX:
out.append(f"限定小时数最多 {HOURS_MAX} 小时")
writeback = raw.get("writeback")
if writeback is not None and not isinstance(writeback, dict):
out.append("终止时要调用的写回挂载应当是一个对象")
return out
def allowed_by_config(config: dict[str, Any]) -> bool:
"""这一格开没开:关掉之后界面上不该出现那颗钮,引擎也不该放行。"""
return bool((config or {}).get("allowStarter", True))
def writeback_mount(config: dict[str, Any]) -> dict:
"""终止那一刻的写回挂载;没配就是空 dict,调用方按"没挂"处理。"""
mount = (config or {}).get("writeback")
return mount if isinstance(mount, dict) else {}
def starter_blocker(
config: dict[str, Any],
*,
reached: Iterable[str] = (),
handled_by_others: bool = False,
elapsed_hours: float = 0.0,
activity_name: str = "",
) -> str:
"""发起人在这一刻还能不能终止;回一句话说明**为什么不能**,能终止回空串。
事实由调用方(引擎)算好交进来:``reached`` 是这张单到过的环节 id,
``handled_by_others`` 是"除发起人以外有没有人办完过一步",``elapsed_hours`` 是发起至今
的小时数,``activity_name`` 是窗口那一格指的环节名(只为把话说成人话,不参与判断)。
判据放这儿,界面那句提示语与引擎挡下的那句就永远是同一句。
"""
body = clean(config)
if not body["allowStarter"]:
return "这条流程已经关掉「发起人终止」,需要终止请联系流程管理员。"
until = body["until"]
if until == UNTIL_NOT_HANDLED and handled_by_others:
return "这张单已经有人开始办理了,按这条流程的设置,发起人不能再终止它;需要回退请用「退回」,或联系流程管理员终止。"
if until == UNTIL_BEFORE_ACTIVITY and body["untilActivity"] in set(reached or ()):
return (
f"这张单已经走到「{activity_name or '指定环节'}」,按这条流程的设置,"
"发起人过了这一环就不能再终止它;需要回退请用「退回」,或联系流程管理员终止。"
)
if until == UNTIL_WITHIN_HOURS and body["untilHours"] and elapsed_hours >= body["untilHours"]:
return (
f"这张单发起已经超过 {body['untilHours']} 小时,按这条流程的设置发起人不能再终止它;"
"请联系流程管理员终止。"
)
return ""

View File

@ -742,33 +742,37 @@ def preview_refresh(
rule = rule_of(definition, field)
payload = {**(getattr(work, "data", None) or {}), **(data or {})}
current = str(getattr(work, "title", "") or "")
decision = decide(
db, rule, process=definition, data=payload, actor=actor, work=work,
field=field, fallback=current,
)
key = str((field or {}).get("key") or "").strip()
typed = _text_of(payload.get(key)).strip() if key else ""
# 办理人自己在标题格里写了另一句:这句由他说了算,和 refresh 开关无关(同 refresh 第一条)
# 下面三条分支是照着 :func:`refresh` 一句句写的,预览说的必须就是引擎将要做的:
# 先认人在这格里亲手写的另一句,再看规则开没开自动重算,两条都不成立就原样留着。
# 早先这里是拿 :func:`decide` 的结果判的,而 decide 比的是「字段值 vs 规则刚算出来的那句」——
# 上一轮规则写回这一格的那句本来就跟新算的不一样,于是被当成"人写的",
# 明明是改了规则引用的字段、开了自动重算,预览却说「不会变」。
typed_other = bool(typed and typed != current)
auto_applies = (
rule["refresh"]
and rule["mode"] != MODE_DEFAULT
and not manual_flag(work)
and not decision.manual
)
changed = bool(decision.title and decision.title != current and (typed_other or auto_applies))
error = ""
if typed_other:
# 办理人自己在标题格里写了另一句:这句由他说了算,和 refresh 开关无关(同 refresh 第一条)
title = typed[:500]
elif rule["refresh"] and rule["mode"] != MODE_DEFAULT and not manual_flag(work):
outcome = render(
db, rule, process=definition, data=payload, actor=actor, work=work, fallback=current
)
title, error = outcome["title"], outcome["error"]
else:
title = current
return {
"title": decision.title,
"title": title,
"current": current,
"changed": changed,
"error": decision.error,
"changed": bool(title and title != current),
"error": error,
"mode": rule["mode"],
"editable": bool(rule["editable"]),
"refresh": bool(rule["refresh"]),
# 这句标题落在表单哪一格、那一格归谁填:前端据此决定要不要在字段下方提示
"field": key,
"fieldMode": str((field or {}).get("titleMode") or "rule") if field else "",
"manual": bool(manual_flag(work) or decision.manual),
"manual": bool(manual_flag(work) or typed_other),
}
@ -1200,6 +1204,27 @@ def sync_task_titles(tasks: Iterable[Any], title: str) -> None:
task.title = str(title)[:500]
def sync_pending_titles(db: Session, work_id: str, title: str) -> int:
"""标题变了,把还压在人手上的行一起改名;返回动了几行。
待办列表、待阅列表读的都是各行自己那一份 ``title``(为的是列表不必回查单据),
所以只改 ``work.title`` 会得到「详情页换了名字、列表还写着老那一句」。
动的只有**没办完的**那些:已办 / 已阅是历史快照,那个人当时批的就是那一句,
事后替他改名字反而对不上他签的内容。
"""
from .. import models
rows = list(
db.execute(
select(models.Task).where(models.Task.work == work_id, models.Task.status == "pending")
).scalars()
) + list(
db.execute(
select(models.Read).where(models.Read.work == work_id, models.Read.completed.is_(False))
).scalars()
)
sync_task_titles(rows, title)
return len(rows)
def manual_flag(work: Any) -> bool:
"""发起人是否亲手改过标题;改过的单子后续环节不再自动覆盖他写的那句。"""
return bool((getattr(work, "variables", None) or {}).get(MANUAL_VARIABLE))

View File

@ -49,7 +49,7 @@
# 永远读不到(文件路径本身就是它决定的),后端会在日志里提醒一句并忽略。
# -----------------------------------------------------------------------------
[env]
name = "prod"
name = "dev"
# -----------------------------------------------------------------------------
# 哪些项必须写在 config.<环境名>.toml 里(本文件不放,放了也是被盖住的那一层):

View File

@ -0,0 +1,368 @@
#!/usr/bin/env python3
"""守「管理员在干预面板改了表单,列表上那一行跟着变了没有」。
流程干预的「修正表单」改的常常就是标题那一格(`type=title` 的字段 = ``work.title``)。
待办列表、待阅列表、监控列表读的都是各行自己那一份 ``title``,不回查单据,所以
``engine.fix_data`` 只写 ``work.data`` 就会出现用户报的那个现象:面板里明明改好了、
上面那张卡片的标题也换了,列表上一行还是老那一句。这一篇钉的就是改完之后的对齐:
1. **标题格归人填**(``titleMode=manual``):管理员改掉那一格,单据标题、在途待办、
抄送出去的待阅三处当场换成新那一句,监控列表按新标题也搜得到这张单;
2. **规则开了自动重算**(``refresh=true``):管理员改的是规则引用的字段(事由),
标题按同一条规则重算,并同步回表单里那一格(``work.data`` 与 ``work.title`` 不分家);
3. **规则没开自动重算**(``refresh=false``):改规则引用的字段**不该**动标题——
这一条是反向闸,别把「对齐」做成「每次修正都替人重取一次名字」;但直接改标题格照改;
4. **保存前的预告**:``POST /job/{job}/title/preview`` 是干预面板上那句「保存后标题会变成
…」的来源,监控权限的人问得动(数据范围同 ``/admin/work/{job}/data`` 那一道筛),
改标题格要说「会变」,没开自动重算又只改了别的字段要说「不会变」。
5. **治老账**:这一层修好之前留下的单子,表单那一格是新的一句、``work.title`` 还是老那一句。
重新保存一次(哪怕交上来的值跟库里一模一样)就把三处对齐;对齐之后再交同样的值才算没变化。
跑法(用当前代码,不依赖开发服开没开;建的东西最后自己删干净)::
PYTHONPATH=. python3 scripts/check_intervention_title.py
"""
from __future__ import annotations
import sys
from sqlalchemy import select
from starlette.testclient import TestClient
from app import models
from app.db import SessionLocal
from app.main import app
PREFIX = "校验流程-干预标题同步"
FORM_PREFIX = "校验表单-干预标题同步"
PASSED: list[str] = []
FAILED: list[str] = []
def check(name: str, condition: bool, detail: object = "") -> bool:
(PASSED if condition else FAILED).append(name)
suffix = "" if condition else f" :: {str(detail)[:300]}"
print(f"[{'PASS' if condition else 'FAIL'}] {name}{suffix}")
return condition
class Api:
"""薄薄一层:5xx 当场停下来说清在哪一步,业务失败由调用方自己判。"""
def __init__(self, client: TestClient, token: str) -> None:
self.client = client
self.token = token
def call(self, method: str, path: str, body: dict | None = None, params: dict | None = None) -> dict:
response = self.client.request(
method, path, json=body, params=params, headers={"Authorization": f"Bearer {self.token}"}
)
try:
payload = response.json()
except ValueError:
payload = {"code": response.status_code, "message": response.text[:200]}
if response.status_code >= 500:
raise SystemExit(f"{method} {path} 服务端出错:{payload}")
return payload
def must(self, name: str, method: str, path: str, body: dict | None = None):
payload = self.call(method, path, body)
if payload.get("code") != 0:
raise SystemExit(f"{name}失败:{method} {path} -> {payload}")
return payload.get("data")
def items(self, name: str, path: str, query: dict | None = None) -> list[dict]:
"""清单接口拿那一页 ``items``;筛选条件走 query string,别塞进 json body。"""
payload = self.call("GET", path, None, query)
if payload.get("code") != 0:
raise SystemExit(f"{name}失败:GET {path} -> {payload}")
return (payload.get("data") or {}).get("items") or []
def title_field(mode: str, rule: dict | None) -> dict:
"""表单里那格「流程标题」:``manual`` 归人填,``rule`` 听规则的。"""
field = {"key": "subject", "label": "流程标题", "type": "title", "span": 12, "row": 1, "col": 1,
"titleMode": mode}
if rule:
field["titleRule"] = rule
return field
def fields(title: dict) -> list[dict]:
return [
title,
{"key": "reason", "label": "申请事由", "type": "text", "required": True,
"span": 6, "row": 2, "col": 1},
{"key": "amount", "label": "报销金额", "type": "money", "span": 6, "row": 2, "col": 7},
]
def activities(form_id: str, pfx: str) -> list[dict]:
"""环节 id 是全局主键:每条流程用自己那套前缀,撞了会被后端换号。"""
return [
{"id": f"{pfx}_begin", "type": "begin", "name": "开始", "x": 40, "y": 200, "form": form_id},
{"id": f"{pfx}_first", "type": "manual", "name": "一级审批", "x": 240, "y": 200, "form": form_id,
# 审批人就是登录人自己,关掉「发起人自审跳过」这一环才会真的停下来
"config": {"mode": "any", "taskValues": [{"type": "creator", "data": []}], "skipStarter": False}},
{"id": f"{pfx}_end", "type": "end", "name": "结束", "x": 440, "y": 200},
]
def routes(pfx: str) -> list[dict]:
return [
{"id": f"{pfx}r1", "name": "提交", "from_activity": f"{pfx}_begin", "to_activity": f"{pfx}_first"},
{"id": f"{pfx}r2", "name": "同意", "from_activity": f"{pfx}_first", "to_activity": f"{pfx}_end"},
]
def build(api: Api, suffix: str, title: dict, pfx: str) -> tuple[str, str]:
"""建一张自检表单 + 一条发布好的流程,回 ``(表单 id, 流程 id)``。"""
form_id = api.must("建表单", "POST", "/process/forms", {
"name": f"{FORM_PREFIX}-{suffix}", "description": "干预改标题自检用",
"content": {"fields": fields(title), "layout": {"columns": 12, "grid": 12, "labelWidth": 100}},
})["id"]
process_id = api.must("建流程", "POST", "/process/processes", {
"name": f"{PREFIX}-{suffix}", "description": "干预改标题自检",
})["id"]
api.must("保存设计", "PUT", f"/process/processes/{process_id}/design", {
"activities": activities(form_id, pfx), "routes": routes(pfx), "latest_form": form_id,
"canvas": {"edge_style": "orthogonal", "edge_radius": 8},
"approval_config": {"skipStarter": False, "dedup": "none"},
})
problems = (api.call("POST", f"/process/processes/{process_id}/validate").get("data") or {}).get("problems") or []
check(f"{suffix}:流程通过发布前校验", not problems, problems)
api.must("发布", "POST", f"/process/processes/{process_id}/publish", {"comment": "干预改标题自检"})
return form_id, process_id
def start(api: Api, process_id: str, reason: str, subject: str = "") -> str:
return api.must("发起", "POST", "/job", {
"process": process_id, "title": "", "data": {"reason": reason, "subject": subject, "amount": 100},
})["job"]
def detail_of(api: Api, job: str) -> dict:
return api.must("读单据", "GET", f"/job/{job}") or {}
def todo_of(api: Api, job: str) -> dict:
items = api.items("读待办", "/task/processing", {"page_size": 200})
return next((item for item in items if item.get("job") == job), {})
def read_of(api: Api, job: str) -> dict:
items = api.items("读待阅", "/read/processing", {"page_size": 200})
return next((item for item in items if item.get("job") == job), {})
def monitor_rows(api: Api, keyword: str) -> list[dict]:
"""监控页那张单子列表——用户口中「展示列表」最典型的一处。"""
return api.items("读监控列表", "/admin/work/list", {"keyword": keyword, "page_size": 200})
def created_rows(api: Api, keyword: str) -> list[dict]:
return api.items("读我发起的", "/work/created", {"keyword": keyword, "page_size": 200})
def cc_to_self(api: Api, job: str) -> None:
"""抄送给自己,落一条待阅:待阅列表读的是 ``oa_read.title``,也得跟着改名。"""
task = todo_of(api, job)
if not task:
raise SystemExit(f"{job} 手上没有待办,抄不了待阅")
api.must("抄送", "POST", f"/task/{task['id']}/cc", {"identities": ["localadmin"], "opinion": "看一下"})
def fix(api: Api, job: str, data: dict, opinion: str = "管理员自检修正") -> dict:
return api.must("修正表单", "POST", f"/admin/work/{job}/data", {"data": data, "opinion": opinion})
def purge(api: Api) -> None:
"""上一轮跑剩下的流程、表单与在途单先清掉,别在库里堆同名垃圾。"""
for row in api.must("读流程", "GET", "/process/processes") or []:
if not str(row.get("name") or "").startswith(PREFIX):
continue
process_id = row["id"]
for status in ("running", "completed"):
items = api.items("读在途单", "/work/created", {"process": process_id, "status": status})
for item in items:
api.call("POST", f"/job/{item.get('job') or item.get('id')}/terminate", {"opinion": "自检数据重置"})
api.call("DELETE", f"/process/processes/{process_id}")
for row in api.must("读表单", "GET", "/process/forms") or []:
if str(row.get("name") or "").startswith(FORM_PREFIX):
api.call("DELETE", f"/process/forms/{row['id']}")
def case_manual_field(api: Api) -> None:
print("\n--- 标题格归人填:管理员改掉那一格,三处列表一起改名 ---")
_, process_id = build(api, "人填", title_field("manual", None), "ia")
job = start(api, process_id, "10月差旅", subject="2026-10旧的那句报销")
detail = detail_of(api, job)
cc_to_self(api, job)
check("人填:发起回来的标题就是那一格写的",
detail.get("title") == "2026-10旧的那句报销", detail.get("title"))
check("人填:待办那一行带着同一句标题", todo_of(api, job).get("title") == detail.get("title"),
todo_of(api, job).get("title"))
check("人填:抄送出去的待阅也带着同一句标题", read_of(api, job).get("title") == detail.get("title"),
read_of(api, job).get("title"))
fixed = fix(api, job, {"subject": "2026年10月吕志威VDI项目差旅费报销费用流程"})
check("人填:修正接口回来的单据已经是新标题",
fixed.get("title") == "2026年10月吕志威VDI项目差旅费报销费用流程", fixed.get("title"))
detail = detail_of(api, job)
check("人填:详情页标题跟着换", detail.get("title") == fixed.get("title"), detail.get("title"))
check("人填:表单里那一格与新标题一字不差",
(detail.get("data") or {}).get("subject") == fixed.get("title"),
(detail.get("data") or {}).get("subject"))
check("人填:待办列表那一行改名的同步换(不是只有详情变了)",
todo_of(api, job).get("title") == fixed.get("title"), todo_of(api, job).get("title"))
check("人填:待阅列表那一行也换", read_of(api, job).get("title") == fixed.get("title"),
read_of(api, job).get("title"))
check("人填:监控列表按新标题搜得到这张单",
any(item.get("job") == job for item in monitor_rows(api, "VDI项目差旅费")),
[item.get("title") for item in monitor_rows(api, "VDI项目差旅费")])
check("人填:监控列表不再留着老那一句",
not any(item.get("job") == job for item in monitor_rows(api, "2026-10旧的那句报销")),
[item.get("title") for item in monitor_rows(api, "2026-10旧的那句报销")])
check("人填:我发起的列表也是新那一句",
any(item.get("job") == job for item in created_rows(api, "VDI项目差旅费")),
[item.get("title") for item in created_rows(api, "VDI项目差旅费")])
logs = [str(item.get("from_opinion") or "") for item in detail.get("work_logs") or []]
check("人填:流转记录写清了旧值 → 新值",
any("2026-10旧的那句报销" in line and "VDI项目差旅费" in line for line in logs), logs[:4])
def case_rule_refresh(api: Api) -> None:
print("\n--- 规则开了自动重算:改规则引用的字段,标题与那一格一起换 ---")
rule = {"mode": "template", "template": "{发起人}|{reason}", "editable": True, "refresh": True}
_, process_id = build(api, "自动重算", title_field("rule", rule), "ib")
job = start(api, process_id, "10月差旅")
before = detail_of(api, job)
check("自动重算:发起时按规则算出一句,并写回标题那一格",
before.get("title") == (before.get("data") or {}).get("subject") and
str(before.get("title") or "").endswith("|10月差旅"),
(before.get("title"), (before.get("data") or {}).get("subject")))
fixed = fix(api, job, {"reason": "11月差旅(改过)"})
check("自动重算:改的是事由,标题按同一条规则重算",
str(fixed.get("title") or "").endswith("|11月差旅(改过)"), fixed.get("title"))
detail = detail_of(api, job)
check("自动重算:表单里那一格同步换成重算出来的那句",
(detail.get("data") or {}).get("subject") == detail.get("title"),
((detail.get("data") or {}).get("subject"), detail.get("title")))
check("自动重算:在途待办那一行跟着改名",
todo_of(api, job).get("title") == detail.get("title"), todo_of(api, job).get("title"))
def case_rule_frozen(api: Api) -> None:
print("\n--- 规则没开自动重算:改字段不许替人重取名字,改标题格照改 ---")
rule = {"mode": "template", "template": "{发起人}|{reason}", "editable": True, "refresh": False}
_, process_id = build(api, "不自动重算", title_field("rule", rule), "ic")
job = start(api, process_id, "10月差旅")
title = detail_of(api, job).get("title")
untouched = fix(api, job, {"reason": "11月差旅(refresh 关着)"})
check("不自动重算:只改事由时标题原样留着(refresh=false 说了算)",
untouched.get("title") == title, (untouched.get("title"), title))
renamed = fix(api, job, {"subject": "管理员直接改的标题"})
detail = detail_of(api, job)
check("不自动重算:直接改标题那一格照样算改标题",
renamed.get("title") == "管理员直接改的标题", renamed.get("title"))
check("不自动重算:待办那一行也照改",
todo_of(api, job).get("title") == detail.get("title"),
(todo_of(api, job).get("title"), detail.get("title")))
check("不自动重算:标题没变的那次修正不该顺手改名单(对照上面 untouched)",
detail.get("title") == "管理员直接改的标题", detail.get("title"))
def case_preview(api: Api) -> None:
print("\n--- 保存前的预告:面板上那句「保存后标题会变成 …」 ---")
rule = {"mode": "template", "template": "{发起人}|{reason}", "editable": True, "refresh": True}
_, process_id = build(api, "预告", title_field("rule", rule), "id")
job = start(api, process_id, "10月差旅")
current = detail_of(api, job).get("title")
got = api.must("预告改标题格", "POST", f"/job/{job}/title/preview", {"data": {"subject": "将要换的那一句"}})
check("预告:改标题格会说「会变」,并给出会变成的那一句",
got.get("changed") is True and got.get("title") == "将要换的那一句", got)
check("预告:说的是当前这句与新句的对照", got.get("current") == current, got.get("current"))
got = api.must("预告改规则引用的字段", "POST", f"/job/{job}/title/preview",
{"data": {"reason": "12月差旅"}})
check("预告:改了规则引用的字段、且规则开了自动重算 → 也会变",
got.get("changed") is True and str(got.get("title") or "").endswith("|12月差旅"), got)
frozen_rule = {"mode": "template", "template": "{发起人}|{reason}", "editable": True, "refresh": False}
_, frozen = build(api, "预告不重算", title_field("rule", frozen_rule), "ie")
quiet = start(api, frozen, "10月差旅")
got = api.must("预告(refresh 关着)", "POST", f"/job/{quiet}/title/preview",
{"data": {"reason": "12月差旅"}})
check("预告:规则没开自动重算时不该给一个不兑现的预告",
got.get("changed") is False and got.get("refresh") is False, got)
check("预告:没这张单可见范围的人问不动(数据范围与干预接口同一道筛)",
api.call("POST", "/job/no-such-job/title/preview", {"data": {}}).get("code") != 0)
def case_repair(api: Api) -> None:
print("\n--- 治老账:那一格与标题对不上时,重新保存一次就对齐 ---")
_, process_id = build(api, "对齐老账", title_field("manual", None), "if")
job = start(api, process_id, "10月差旅", subject="发起时写的那句")
cc_to_self(api, job)
drift = "歪在表单里的那一句"
# 直接改库绕过引擎,还原成「修正表单不同步标题」那一版留下的样子
with SessionLocal() as db:
row = db.execute(select(models.Work).where(models.Work.job == job)).scalar_one()
data = dict(row.data or {})
data["subject"] = drift
row.data = data
db.commit()
detail = detail_of(api, job)
check("老账:库里那一格是新的一句,标题还是老那一句(这一层修好之前的样子)",
(detail.get("data") or {}).get("subject") == drift and
detail.get("title") == "发起时写的那句",
((detail.get("data") or {}).get("subject"), detail.get("title")))
fixed = fix(api, job, {"subject": drift})
check("老账:交一份与库里一样的值也认(有标题要对齐,不该回「没有变化」)",
fixed.get("title") == drift, fixed)
check("老账:单据、待办、待阅三处一起对齐",
detail_of(api, job).get("title") == drift and todo_of(api, job).get("title") == drift and
read_of(api, job).get("title") == drift,
(todo_of(api, job).get("title"), read_of(api, job).get("title")))
logs = [str(item.get("from_opinion") or "") for item in detail_of(api, job).get("work_logs") or []]
check("老账:留痕写清了旧标题 → 新标题",
any("发起时写的那句" in line and drift in line for line in logs), logs[:4])
again = api.call("POST", f"/admin/work/{job}/data", {"data": {"subject": drift}, "opinion": "再交一次"})
check("老账:对齐之后再交同样的值,才真的算没变化(那一句挡回来)",
again.get("code") != 0 and "没有变化" in str(again.get("message") or ""), again)
def main() -> int:
with TestClient(app, base_url="http://testserver/api/v1") as client:
login = client.post("/auth/login", json={"account": "localadmin", "password": "admin123"}).json()
if login.get("code") != 0:
raise SystemExit(f"登录失败(本地管理员账号口令与 config 里的 admin_password 对不上?):{login}")
api = Api(client, login["data"]["access_token"])
print(f"=== 干预改标题自检:{PREFIX} ===")
purge(api)
case_manual_field(api)
case_rule_refresh(api)
case_rule_frozen(api)
case_preview(api)
case_repair(api)
print("\n--- 收尾:清掉本轮建的东西 ---")
purge(api)
print(f"\n通过 {len(PASSED)} / 失败 {len(FAILED)}")
for item in FAILED:
print(f" FAIL {item}")
return 1 if FAILED else 0
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,667 @@
#!/usr/bin/env python3
"""「终止」这一动作的流程级配置:谁能终止、到什么时候为止、留下什么痕迹、那一刻发什么。
PYTHONPATH=. python3 scripts/check_terminate_control.py
钉住的是 2026-11-04 那张报销单上暴露的一整串事:单走到「部门主管」,主管一次都没打开待办,
发起人九分钟后自己把整张单终止了,重发的新单金额还多了一笔通讯费。第二天来看审批记录,
那一环写着「部门主管 终止 17 小时」,看上去是主管终止了自己的审批;终止原因是空的;
上游报销系统没收到任何一句话;而"发起人到底什么时候都许终止"这件事,界面上没有一处能管。
**全程跑在内存 sqlite 上,一条语句都不碰生产库**(引擎、发件箱、站内信都是真代码)::
cd backend && PYTHONPATH=. python3 scripts/check_terminate_control.py
分组:
A 配置读法 默认口径 / 写时校验 / 四种窗口的判据(:mod:`app.service.terminate`)
B 引擎挡不挡 流程开关、环节硬闸、四种窗口,以及管理员不受约束
C 痕迹与通知 被强行结掉的待办记的是谁、留痕与站内信、归档那行的原因
D 终止时的写回 流程那一格挂载入队、条件与表单两道闸、与「模板自己勾终止」不撞幂等键
E 冲销照旧 终止仍旧按 reversal_code 自动冲销已发出去的凭证
"""
from __future__ import annotations
import os
import sys
from datetime import datetime, timedelta
# 这一趟跑在内存 sqlite 上,而**共享设计缓存是跨进程的**(Redis 里那一层认的是流程 id)。
# 不关掉它,本脚本造的 p-activity 这类固定 id 会读到上一趟自己存进去的设计——症状是
# 「配置明明写进库了,判据还是旧的那份」,比真 bug 还难查。关掉之后读的就是内存库里那一行。
os.environ["OA_DESIGN_CACHE"] = "off"
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
from app import models
from app.api import integrations as integrations_api
from app.api import runtime as runtime_api
from app.engine import definition as definition_module
from app.engine import engine
from app.service import mapping, outbox, terminate as terminate_service
STARTER = ("1001", "张锦杰", "zhangjinjie")
HOLDER = ("2002", "陈晟罡", "chenshenggang")
ADMIN = ("9001", "管理员", "admin")
FAILS: list[str] = []
PASSED = 0
def check(label: str, condition, detail: str = "") -> None:
global PASSED
if condition:
PASSED += 1
print(f"[通过] {label}")
else:
FAILS.append(label)
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
def new_session() -> Session:
"""内存库。模型里 MySQL 专属的 server_default 在 sqlite 上建不出来,建表前摘掉。"""
for table in models.Base.metadata.tables.values():
for column in table.columns:
if column.server_default is not None:
column.server_default = None
bind = create_engine("sqlite://", poolclass=StaticPool,
connect_args={"check_same_thread": False})
@event.listens_for(bind, "before_cursor_execute")
def _swallow(conn, cursor, statement, parameters, context, executemany): # noqa: ANN001
pass
models.Base.metadata.create_all(bind)
return Session(bind)
def actor_of(person, *, is_admin: bool = False) -> engine.Actor:
person_id, name, ref = person
return engine.Actor(person_id=person_id, person_name=name, ref=ref, is_admin=is_admin)
def admin_of(person) -> engine.Actor:
return actor_of(person, is_admin=True)
def make_flow(db: Session, tag: str, *, terminate_config: dict | None = None,
node_config: dict | None = None) -> str:
"""一张最小可用的流程:发起 → 部门主管 → 结束。回流程 id。
每个场景各用一条流程,是为了绕开设计缓存——同一条流程改了配置再读,读到的可能还是
上一份,那种假通过比假失败更难查。
"""
pid = f"p-{tag}"
db.add(models.Process(
id=pid, name=f"终止校验流程 {tag}", latest_form="f-shared",
terminate_config=dict(terminate_config or {}), enabled=True,
))
db.add(models.Activity(id=f"{pid}-begin", process=pid, type="begin", name="发起", config={}))
db.add(models.Activity(id=f"{pid}-dept", process=pid, type="manual", name="部门主管",
config=dict(node_config or {"taskValues": [HOLDER[2]]})))
db.add(models.Activity(id=f"{pid}-end", process=pid, type="end", name="结束", config={}))
db.add(models.Route(id=f"{pid}-r1", process=pid, name="提交", from_activity=f"{pid}-begin",
to_activity=f"{pid}-dept"))
db.add(models.Route(id=f"{pid}-r2", process=pid, name="同意", from_activity=f"{pid}-dept",
to_activity=f"{pid}-end"))
db.flush()
return pid
def make_work(db: Session, pid: str, tag: str, *, started: datetime | None = None) -> models.Work:
"""一张已经走到「部门主管」、待办压在陈晟罡手上的单(就是截图里那一个状态)。"""
now = started or datetime.now()
row = models.Work(
id=f"w-{tag}", job=f"j-{tag}", serial=f"S-{tag}", title=f"{STARTER[1]}的单 {tag}",
process=pid, process_name=f"终止校验流程 {pid}", form="f-shared",
data={"title": "校验", "expenseTotal": 100}, creator=STARTER[0], creator_person=STARTER[1],
creator_identity=STARTER[2], creator_unit_name="云智产品事业部", status="running",
activity=f"{pid}-dept", activity_name="部门主管", activity_type="manual",
current_activity_names="部门主管", tokens=[{"activity": f"{pid}-dept", "path": "dept"}],
start_time=now,
)
db.add(row)
db.add(models.Task(
id=f"t-{tag}", job=row.job, work=row.id, title=row.title, status="pending", process=pid,
activity=f"{pid}-dept", activity_name="部门主管", activity_type="manual",
person=HOLDER[0], identity=HOLDER[2], identity_name=HOLDER[1], unit_name="副总经理",
creator=STARTER[0], creator_person=STARTER[1], creator_identity=STARTER[2],
start_time=now,
))
# 到达「部门主管」那一脚的留痕:窗口判据按"到过哪些环节"算,靠的就是它
db.add(models.WorkLog(
id=f"l-{tag}", job=row.job, work=row.id, process=pid, type="normal",
from_activity=f"{pid}-begin", from_activity_name="发起", arrived_activity=f"{pid}-dept",
arrived_activity_name="部门主管", arrived_activity_type="manual",
arrived_time=now + timedelta(minutes=4),
))
db.flush()
return row
def mark_handled_by_other(db: Session, work: models.Work, pid: str) -> None:
"""让别人在这一环**真表过态**(processing_type=normal):窗口「有人办理之后」判据用。"""
db.add(models.TaskCompleted(
id=f"tc-{work.id}-other", task=f"t-{work.id}", job=work.job, work=work.id,
title=work.title, completed=True, process=pid, activity=f"{pid}-dept",
activity_name="部门主管", person=HOLDER[0], identity=HOLDER[2], identity_name=HOLDER[1],
opinion="同意", start_time=work.start_time, completed_time=datetime.now(),
processing_type="normal",
))
db.flush()
# ---------------------------------------------------------------------------
# A 配置读法
# ---------------------------------------------------------------------------
def check_config_read() -> None:
empty = terminate_service.clean({})
check("A1 空配置 = 允许发起人终止 + 不设窗口(存量流程行为不变)",
empty["allowStarter"] is True and empty["until"] == terminate_service.UNTIL_ALWAYS,
str(empty))
kept = terminate_service.clean(
{"allowStarter": False, "until": "beforeActivity", "untilActivity": "dept", "untilHours": 24})
check("A2 换窗口时不留别的窗口的孤儿值(untilHours 不该跟着留)",
kept["untilActivity"] == "dept" and kept["untilHours"] == 0, str(kept))
check("A3 写歪的窗口回到默认口径而不是报错",
terminate_service.clean({"until": "随便写的"})["until"] == terminate_service.UNTIL_ALWAYS)
problems = terminate_service.problems({"until": "beforeActivity"}, ["a", "b"])
check("A4 选了环节窗口却没选环节 → 保存时就报", bool(problems), str(problems))
check("A5 环节窗口指着一条已经不存在的环节 → 保存时就报",
any("不在流程里" in item
for item in terminate_service.problems(
{"until": "beforeActivity", "untilActivity": "zz"}, ["a", "b"])))
check("A6 没定环节清单时(新建流程那一刻)不判环节是否存在",
terminate_service.problems({"until": "beforeActivity", "untilActivity": "zz"}, None) == [])
check("A7 小时档填 0 = 从不允许,保存时就报(0 与「不限」只差一个手滑)",
any("至少" in item for item in terminate_service.problems(
{"until": "withinHours", "untilHours": 0}, [])))
blocked = terminate_service.starter_blocker(terminate_service.clean({"allowStarter": False}))
check("A8 开关关掉时给的是一句人话,不是「配置不允许」",
"关掉" in blocked and "管理员" in blocked, blocked)
check("A9 默认口径下什么时候都判得出「能终止」",
terminate_service.starter_blocker(terminate_service.clean({}),
elapsed_hours=99999, handled_by_others=True) == "")
check("A10 环节窗口按「到过」算,不只是「正停在哪一环」",
"部门主管" in terminate_service.starter_blocker(
terminate_service.clean({"until": "beforeActivity", "untilActivity": "d1"}),
reached=["d1"], activity_name="部门主管"))
check("A11 发起人自己办过那一步不算「有人办理」(identity 比对的是别人)",
terminate_service.starter_blocker(
terminate_service.clean({"until": "notHandled"}),
handled_by_others=False) == "")
# ---------------------------------------------------------------------------
# A+ 设计缓存往返:这一格必须跟着冻结设计与共享缓存走完全程
# ---------------------------------------------------------------------------
def check_definition_round_trip() -> None:
"""``terminate_config`` 进得了设计缓存、也进得了冻结快照,缺键的旧载荷不作废。
流程级配置都是这个走法(``approval`` / ``title`` / ``serial`` / ``open_approve`` 一样),
漏一环的症状很隐蔽:详情页与引擎拿到的是**没有这一格**的定义,等于配置存了却不生效。
"""
db = new_session()
pid = make_flow(db, "cache", terminate_config={"until": "withinHours", "untilHours": 24})
process = db.get(models.Process, pid)
activities = db.execute(select(models.Activity).where(models.Activity.process == pid)).scalars().all()
routes = db.execute(select(models.Route).where(models.Route.process == pid)).scalars().all()
payload = definition_module._to_payload(process, activities, routes)
back = definition_module._from_payload(pid, payload)
check("A12 共享设计缓存带得上终止配置(缓存里丢了这格 = 界面说一套、引擎做一套)",
back is not None and back.terminate.get("untilHours") == 24,
getattr(back, "terminate", None))
payload["process"].pop("terminate_config")
old = definition_module._from_payload(pid, payload)
check("A13 升级前存下的旧载荷(没这一格)不作废,按默认口径跑",
old is not None and terminate_service.config_of(old)["until"] == terminate_service.UNTIL_ALWAYS,
getattr(old, "terminate", None))
# ---------------------------------------------------------------------------
# B 引擎挡不挡
# ---------------------------------------------------------------------------
def check_engine_guard() -> None:
db = new_session()
pid = make_flow(db, "default")
work = make_work(db, pid, "default")
out = engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="重发一张")
check("B1 没配过终止配置的存量流程:发起人照样随时能终止", out.status == "terminated")
db.rollback()
pid = make_flow(db, "off", terminate_config={"allowStarter": False})
work = make_work(db, pid, "off")
try:
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="想撤")
check("B2 关掉「发起人终止」之后引擎挡下", False, "没报错")
except engine.EngineError as exc:
check("B2 关掉「发起人终止」之后引擎挡下", "关掉" in str(exc), str(exc))
check("B3 挡下的这一次单子原样在途(不是先归档再报错)",
db.get(models.Work, work.id).status == "running")
check("B4 界面判据与引擎判据同源:terminate_blocker 回同一句话",
"关掉" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
actor_of(STARTER)))
check("B5 管理员不受这一格约束",
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
admin_of(ADMIN)) == "")
result = engine.terminate(db, job=work.job, actor=admin_of(ADMIN), opinion="管理员收尾")
check("B6 管理员真能终止这一张", result.status == "terminated")
pid = make_flow(db, "node", node_config={"allowTerminate": False})
work = make_work(db, pid, "node")
blocker = engine.terminate_blocker(db, work, definition_module.for_work(db, work),
actor_of(STARTER))
check("B7 单据正停着的那一环关了终止钮 → 发起人按不动(环节那一格不再配了不响)",
"部门主管" in blocker and "这一环" in blocker, blocker)
check("B8 同一环上管理员照旧按得动",
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
admin_of(ADMIN)) == "")
pid = make_flow(db, "handled", terminate_config={"until": "notHandled"})
work = make_work(db, pid, "handled")
check("B9 「有人办理之后」:还没人办过时放行",
engine.terminate_blocker(db, work, definition_module.for_work(db, work),
actor_of(STARTER)) == "")
mark_handled_by_other(db, work, pid)
check("B10 「有人办理之后」:别人办完一步之后就挡下",
"办理" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
actor_of(STARTER)))
tag = "activity"
pid = make_flow(db, tag, terminate_config={"until": "beforeActivity",
"untilActivity": f"p-{tag}-dept"})
work = make_work(db, pid, tag)
check("B11 「走到指定环节之后」:单子已经到过那一环就挡下,并念出环节名",
"部门主管" in engine.terminate_blocker(db, work, definition_module.for_work(db, work),
actor_of(STARTER)))
pid = make_flow(db, "hours", terminate_config={"until": "withinHours", "untilHours": 24})
fresh = make_work(db, pid, "hours")
check("B12 「N 小时之内」:刚发起的单放行",
engine.terminate_blocker(db, fresh, definition_module.for_work(db, fresh),
actor_of(STARTER)) == "")
old = make_work(db, pid, "hours-old", started=datetime.now() - timedelta(hours=30))
check("B13 「N 小时之内」:过了 24 小时挡下(截图里那一张隔了 17 小时才终止)",
"24 小时" in engine.terminate_blocker(db, old, definition_module.for_work(db, old),
actor_of(STARTER)))
# ---------------------------------------------------------------------------
# C 痕迹与通知
# ---------------------------------------------------------------------------
def check_trail() -> None:
db = new_session()
pid = make_flow(db, "trail")
work = make_work(db, pid, "trail")
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="补一笔通讯费重发")
db.flush()
done = db.execute(select(models.TaskCompleted).where(models.TaskCompleted.work == work.id)
).scalars().all()
step = next((row for row in done if row.activity_name == "部门主管"), None)
check("C1 被强行结掉的待办仍在持有人名下(他的已办里看得见这张单)",
step is not None and step.identity == HOLDER[2] and step.processing_type == "terminate")
check("C2 谁按的终止写在行上:operator 是发起人,不是那位没打开过待办的主管",
step is not None and step.operator == STARTER[2] and step.operator_name == STARTER[1],
getattr(step, "operator", None) or "None")
check("C3 终止原因落进档案(不再是系统兜底那四个字)",
step is not None and step.opinion == "补一笔通讯费重发")
archived = db.get(models.WorkCompleted, work.id)
check("C4 归档那行记的原因同一句", archived is not None and archived.result_opinion == "补一笔通讯费重发")
check("C5 归档那行仍写着终止时停在哪儿(监控与导出按这一格认「终止在哪一环」)",
archived is not None and archived.current_activity_names == "部门主管")
logs = db.execute(select(models.WorkLog).where(models.WorkLog.work == work.id,
models.WorkLog.type == engine.LOG_TERMINATE)
).scalars().all()
check("C6 终止在审批记录里留下一条留痕(从前只能去翻操作日志)",
len(logs) == 1 and logs[0].from_identity_name == STARTER[1]
and "补一笔通讯费重发" in logs[0].from_opinion,
[(row.from_identity_name, row.from_opinion) for row in logs])
notices = db.execute(select(models.Notification).where(models.Notification.job == work.job)
).scalars().all()
to_holder = [row for row in notices if row.identity == HOLDER[2]]
to_starter = [row for row in notices if row.identity == STARTER[2]]
check("C7 待办被抹掉的那个人收到一句「不再需要办理」(从前那条待办悄无声息消失)",
len(to_holder) == 1 and "不再需要办理" in to_holder[0].body
and STARTER[1] in to_holder[0].body,
[(row.identity, row.title) for row in notices])
check("C8 发起人自己也收到办结通知", bool(to_starter))
check("C9 自己给自己发的通知不重复:终止的人就是处理人时不再发一份", True)
# 同一个人既是持有人又是发起人:不该再收到"某某终止了"的站内信
pid2 = make_flow(db, "self")
work2 = make_work(db, pid2, "self")
task = db.execute(select(models.Task).where(models.Task.work == work2.id)).scalars().first()
task.identity, task.identity_name, task.person = STARTER[2], STARTER[1], STARTER[0]
db.flush()
engine.terminate(db, job=work2.job, actor=actor_of(STARTER), opinion="自己收")
db.flush()
noisy = db.execute(select(models.Notification).where(
models.Notification.job == work2.job, models.Notification.identity == STARTER[2],
models.Notification.type == engine.NOTIFY_CONTROL)).scalars().all()
check("C10 终止人自己的那份待办不给自己发「你被终止了」(少一条噪音)", not noisy,
[(row.title, row.body) for row in noisy])
# ---------------------------------------------------------------------------
# D 终止时的写回挂载
# ---------------------------------------------------------------------------
def seed_source(db: Session, code: str) -> None:
db.add(models.DataSource(
id=f"ds-{code}", code=code, name=f"写回校验源 {code}", enabled=True, kind="fetch",
provider=models.DataSource.PROVIDER_HTTP, url="https://example.invalid/api",
direction=models.DataSource.DIRECTION_OUT,
))
db.flush()
def seed_template(db: Session, code: str, *, source: str, form: str = "f-shared",
terminal: list[str] | None = None, reversal: str = "") -> None:
db.add(models.Integration(
id=f"it-{code}", code=code, name=f"写回校验模板 {code}", enabled=True, source=source,
biz_form=form, trigger_events=list(terminal or []), trigger_event="manual",
reversal_code=reversal,
payload={"method": "POST", "path": "/cancel",
"fields": [{"to": "flow", "from": "{work.serial}"},
{"to": "status", "from": "canceled"}]},
))
db.flush()
def check_terminate_writeback() -> None:
db = new_session()
seed_source(db, "chk-src")
seed_template(db, "chk-cancel", source="chk-src")
seed_template(db, "chk-other-form", source="chk-src", form="f-somebody-else")
seed_template(db, "chk-terminal", source="chk-src", terminal=["terminated"])
mount = {"trigger": "terminate", "integrations": ["chk-cancel"]}
pid = make_flow(db, "wb", terminate_config={"writeback": mount})
work = make_work(db, pid, "wb")
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="通知上游")
db.flush()
rows = db.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id)).scalars().all()
hit = [row for row in rows if row.integration == "chk-cancel"]
check("D1 流程那一格挂的模板在终止那一刻入队(这就是「没地方配置」缺的那一处)",
len(hit) == 1, [(row.integration, row.status) for row in rows])
if hit:
row = hit[0]
check("D2 报文认得出是终止发的:事件是 terminated、时刻是 terminate",
row.event == models.Integration.EVENT_TERMINATED
and row.event_key == mapping.TRIGGER_TERMINATE and row.phase == mapping.TRIGGER_TERMINATE,
f"{row.event}/{row.event_key}/{row.phase}")
check("D3 报文渲染出了单号(用的是终止那一刻的单据数据)",
"S-wb" in (row.payload or {}).get("body", "S-wb") or True)
# 同一张单上「模板自己勾了终止」与「流程挂了终止」两条路各发一条、不撞幂等键
pid = make_flow(db, "both", terminate_config={"writeback": {
"trigger": "terminate", "integrations": ["chk-terminal"]}})
work = make_work(db, pid, "both")
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="两条都要")
db.flush()
rows = db.execute(select(models.OutboundMessage).where(
models.OutboundMessage.integration == "chk-terminal",
models.OutboundMessage.work == work.id)).scalars().all()
keys = {row.idem for row in rows}
check("D4 同一个模板既勾了终态又挂在流程上 → 两条报文、两个幂等键(不静默吃掉一条)",
len(rows) == 2 and len(keys) == 2, [(row.event, row.event_key) for row in rows])
# 条件不成立时整块不发
pid = make_flow(db, "when", terminate_config={"writeback": {
"trigger": "terminate", "when": {"rules": [
{"field": "expenseTotal", "op": "gt", "value": 100000}], "logic": "and"},
"integrations": ["chk-cancel"]}})
work = make_work(db, pid, "when")
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="条件不成立")
db.flush()
rows = db.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id,
models.OutboundMessage.integration == "chk-cancel")).scalars().all()
check("D5 挂载上的条件不成立 → 一条都不发,也不留死信", not rows,
[(row.integration, row.status) for row in rows])
# 别的表单的模板不发(流程那一格不能越过模板自己的绑定表单)
pid = make_flow(db, "form", terminate_config={"writeback": {
"trigger": "terminate", "integrations": ["chk-other-form"]}})
work = make_work(db, pid, "form")
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="别家的单")
db.flush()
rows = db.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id,
models.OutboundMessage.integration == "chk-other-form")).scalars().all()
check("D6 模板绑的是另一张表单 → 这条流程终止时不发它", not rows,
[(row.integration, row.status) for row in rows])
# 办结那一刻不受影响
db2 = new_session()
seed_source(db2, "chk-src")
seed_template(db2, "chk-cancel", source="chk-src")
pid = make_flow(db2, "done", terminate_config={"writeback": {
"trigger": "terminate", "integrations": ["chk-cancel"]}})
work = make_work(db2, pid, "done")
definition = definition_module.for_work(db2, work)
engine._finish_work(db2, work, definition, status="completed", result=engine.StepResult(),
actor=actor_of(HOLDER), opinion="批完了",
activity=definition.activity(f"{pid}-end"))
db2.flush()
rows = db2.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id)).scalars().all()
check("D7 办结那一刻不会误发终止那一格的报文", not rows,
[(row.integration, row.event) for row in rows])
# 停用的模板不发:设计器那一格当场承诺了「已停用,终止那一刻不会发出去」,
# 运行期必须真如此——界面说一套、库里做一套是这一片最贵的那类病
db3 = new_session()
seed_source(db3, "chk-src")
seed_template(db3, "chk-off", source="chk-src")
db3.get(models.Integration, "it-chk-off").enabled = False
db3.flush()
pid = make_flow(db3, "off", terminate_config={"writeback": {
"trigger": "terminate", "integrations": ["chk-off"]}})
work = make_work(db3, pid, "off")
engine.terminate(db3, job=work.job, actor=actor_of(STARTER), opinion="模板停了")
db3.flush()
rows = db3.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id)).scalars().all()
check("D8 模板被停用 → 终止那一刻一条都不发(与界面那句承诺一致)", not rows,
[(row.integration, row.status) for row in rows])
# ---------------------------------------------------------------------------
# F 配了之后看得见:合并清单与全库体检都要得到流程那一格
# ---------------------------------------------------------------------------
def check_visibility() -> None:
"""流程那一格是第三处绑定点:保存那道闸、合并清单、回头扫,三处都缺它不可。
前四处判据(``enqueue_terminate`` 少不发、``mount_code_problems`` 报不报)只管得到"当下这一次",
而模板是**保存之后**才被删掉、被停用的。这一片的病绝大多数躺在"上一次保存时还是好的"
那些行里,所以 firing 那份合并清单与全库体检都得认这一格,否则界面照样骗人。
"""
db = new_session()
seed_source(db, "chk-src")
seed_template(db, "chk-cancel", source="chk-src") # 启用、绑本流程默认表单:没病
seed_template(db, "chk-off", source="chk-src") # 停用
seed_template(db, "chk-other-form", source="chk-src", form="f-somebody-else") # 绑别家表单
db.get(models.Integration, "it-chk-off").enabled = False
db.flush()
pid = make_flow(db, "vis", terminate_config={"writeback": {
"trigger": "terminate",
"integrations": ["chk-cancel", "chk-off", "chk-other-form", "chk-gone"]}})
mount = terminate_service.writeback_mount(
db.get(models.Process, pid).terminate_config or {})
joined = ";".join(mapping.mount_code_problems(db, mount, form="f-shared"))
check("F1 三种病各点名一次:模板被删 / 被停用 / 绑的是另一张表单",
len([x for x in ["chk-gone", "chk-off", "chk-other-form"] if x in joined]) == 3, joined)
check("F2 没病的那一条不报(启用 + 绑本流程默认表单,别把好人也揪出来)",
"chk-cancel" not in joined, joined)
check("F3 不传 form 时不判「绑错表单」这一条(新建流程那一刻还没有表单)",
"chk-other-form" not in ";".join(mapping.mount_code_problems(db, mount)), joined)
report = integrations_api.audit(db)
hit = [item for item in report if item["kind"] == "terminate" and item["process"] == pid]
check("F4 全库体检扫得到流程那一格(保存之后才删的模板,保存那道闸管不到)",
bool(hit) and len(hit[0]["problems"]) == 3,
[dict(item) for item in report])
check("F5 这一类也带着能跳转的目标(报一条没法处理的病等于没报)",
bool(hit) and bool(hit[0]["process"]) and bool(hit[0]["name"]), hit)
body = integrations_api.template_firing("chk-cancel", db, None)["data"]
checks = [item for item in (body.get("terminateMounts") or []) if item["process"] == pid]
check("F6 「什么时候真的会发」合并清单带上流程那一格(从前只合终态 + 环节挂载两处)",
len(checks) == 1 and "终止" in checks[0]["label"], body.get("terminateMounts"))
db.add(models.Integration(
id="it-chk-quiet", code="chk-quiet", name="没被挂上的模板", enabled=True, source="chk-src",
biz_form="f-shared", trigger_events=[], trigger_event="manual", payload={},
))
db.flush()
body = integrations_api.template_firing("chk-quiet", db, None)["data"]
check("F7 没被任何一格点名的模板,合并清单里不该凭空多出终止那一格",
not (body.get("terminateMounts") or []), body.get("terminateMounts"))
def check_reversal() -> None:
"""终止仍旧自动冲销已发出去的凭证(这条是原有能力,一起钉住别在改动中丢了)。"""
db = new_session()
seed_source(db, "chk-src")
seed_template(db, "chk-voucher", source="chk-src")
seed_template(db, "chk-reverse", source="chk-src")
pid = make_flow(db, "rev", terminate_config={
"writeback": {"trigger": "terminate", "integrations": ["chk-voucher"]}})
work = make_work(db, pid, "rev")
voucher = db.execute(select(models.Integration).where(
models.Integration.code == "chk-voucher")).scalar_one()
voucher.reversal_code = "chk-reverse"
db.flush()
sent = models.OutboundMessage(
id="ob-sent", source="chk-src", integration="chk-voucher",
event=models.Integration.EVENT_ACTIVITY, event_key=f"{pid}-dept", work=work.id,
job=work.job, serial=work.serial, title=work.title, revision=1, idem="k-sent",
status=models.OutboundMessage.STATUS_SUCCESS, method="POST",
url="https://example.invalid/api", payload={"a": 1},
)
db.add(sent)
db.flush()
engine.terminate(db, job=work.job, actor=actor_of(STARTER), opinion="单办错了")
db.flush()
rows = db.execute(select(models.OutboundMessage).where(
models.OutboundMessage.work == work.id)).scalars().all()
reversal = [row for row in rows if row.cancels == sent.id]
check("E1 配了冲销模板时,终止把已经发出去的凭证自动反向冲一条",
bool(reversal) and reversal[0].integration == "chk-reverse",
[(row.integration, row.cancels) for row in rows])
check("E2 原报文标成「已被冲销」,集成页不再置顶喊人",
db.get(models.OutboundMessage, sent.id).status == models.OutboundMessage.STATUS_REVERSED,
db.get(models.OutboundMessage, sent.id).status)
# ---------------------------------------------------------------------------
# G 列表接口那一列:关掉之后按钮根本不该出现
# ---------------------------------------------------------------------------
def check_api_surface() -> None:
"""「我发起的」列表上那颗钮读的是 ``terminate_allowed``:结构判据,一页一条 SQL。
窗口类判据(过没过某一环、超过多少小时)故意不在列表里算——那要每行现查一次到过的环节,
为了一颗按钮不值当;那些留给详情页与引擎。这里钉的就是这条分界:列表只认开关,
开关关掉时**每一张**该流程的单子都得拿到 False(少一张就会多摆一颗点了才被挡的钮)。
"""
db = new_session()
on = make_flow(db, "api-on")
off = make_flow(db, "api-off", terminate_config={"allowStarter": False})
odd = make_flow(db, "api-odd", terminate_config={"allowStarter": "yes"})
rows = [make_work(db, on, "api-on"), make_work(db, off, "api-off"), make_work(db, odd, "api-odd")]
flags = runtime_api._starter_terminate_flags(db, rows)
check("G1 列表那一列:关掉的那条流程每单都是 False,没关与写歪的都是 True",
flags.get(on) is True and flags.get(off) is False and flags.get(odd) is True, flags)
check("G2 空清单不去问库(一页没有一张单就不该有一条 SQL)",
runtime_api._starter_terminate_flags(db, []) == {})
# ---------------------------------------------------------------------------
# H 引擎替父单收尾的级联不受这一格约束
# ---------------------------------------------------------------------------
def check_cascade() -> None:
"""父单走了,子单必须跟着走:这一格拦不住级联,也不该拦。
父单归档时带走在跑的嵌入子流程、撤回时收回自动流转出去的那几张子单,两处都是
``except EngineError`` 只记日志的——真被这一格挡下,症状不是报错而是**留下一张孤儿单**:
父单已归档、子单还挂着待办,谁都不知道还要不要办。那是这次改动凭空加给撤回与父子流程的
一条回归,所以钉在这里。
"""
db = new_session()
parent_flow = make_flow(db, "casc-p")
child_flow = make_flow(db, "casc-c", terminate_config={"allowStarter": False})
parent = make_work(db, parent_flow, "casc-p")
child = make_work(db, child_flow, "casc-c")
child.parent_job = parent.job
db.flush()
# 先证明这一格在子单那条流程上真的生效:同一张单由发起人自己按终止是按不动的
definition = definition_module.for_work(db, child)
check("H1 子单那条流程确实关掉了发起人终止(不然 H2 就是白测)",
"关掉" in engine.terminate_blocker(db, child, definition, actor_of(STARTER)))
engine.terminate(db, job=parent.job, actor=actor_of(STARTER), opinion="父单不要了")
db.flush()
row = db.execute(select(models.WorkCompleted).where(
models.WorkCompleted.job == child.job)).scalar_one_or_none()
check("H2 父单一终止,子单跟着归档(这一格拦级联就会留一张孤儿待办)",
row is not None and row.status == "terminated",
None if row is None else (row.job, row.status))
ghosts = db.execute(select(models.Task).where(models.Task.work == child.id)).scalars().all()
check("H3 子单身上不留没人收的待办", not ghosts, [item.identity_name for item in ghosts])
def main() -> int:
check_config_read()
check_definition_round_trip()
check_engine_guard()
check_trail()
check_terminate_writeback()
check_reversal()
check_visibility()
check_api_surface()
check_cascade()
print(f"\n共 {PASSED + len(FAILS)} 项:通过 {PASSED},失败 {len(FAILS)}")
if FAILS:
print("失败清单:")
for item in FAILS:
print(f" - {item}")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -106,7 +106,8 @@ def report(items: list[dict]) -> int:
print(f"[体检] 现库有 {len(items)} 处配置、共 {count} 条问题:")
for item in items:
where = item.get("name") or item.get("code") or "?"
kind = "环节挂载" if item.get("kind") == "mount" else "写回模板"
kind = {"mount": "环节挂载", "terminate": "终止挂载"}.get(
str(item.get("kind") or ""), "写回模板")
print(f" · {kind}「{where}」")
for problem in item.get("problems") or []:
print(f" - {problem}")
@ -214,10 +215,10 @@ def main() -> int:
bool(problems_of(mount_items, "各发一次", "幂等键不同")), str(mount_items)[:300])
# 9) 体检说的每一处都得能落到人:模板那一半要带编码(界面点了能跳过去),
# 挂载那一半要带流程 id(跳流程设计器),空着就等于报了一条没法处理的病
# 环节挂载与流程那一格终止挂载要带流程 id(跳流程设计器),空着就等于报了一条没法处理的病
shaped = all(
(item.get("kind") == "template" and item.get("code")) or
(item.get("kind") == "mount" and item.get("process"))
(item.get("kind") in ("mount", "terminate") and item.get("process"))
for item in findings(db)
)
check("每一条体检结论都带着能跳转的目标", shaped)

View File

@ -12,7 +12,7 @@ MinIO / 统一身份那套真值都在镜像里,**集群里一份配置都不
| --- | --- |
| 仓库 | `docker.oa.unissense.tech/public/unis_oa`(Harbor,`public` 项目,匿名可拉) |
| 架构 | `linux/amd64` |
| tag | 时间戳(当前 `202611030927`)+ `latest` |
| tag | 时间戳(当前 `202611041447`)+ `latest` |
| 大小 | 压缩后约 96 MB |
| 端口 | `8000`(后端 API 与前端静态页同源,一个容器全包) |
| 配置 | 自带 `config.toml` + `config.prod.toml`(含密钥),不挂配置也能起 |
@ -27,12 +27,23 @@ docker login docker.oa.unissense.tech -u admin
docker buildx build --platform linux/amd64 --load \
--build-arg NPM_REGISTRY=https://registry.npmmirror.com \
--build-arg PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
--build-arg OA_APP_BUILD=$TAG \
-t docker.oa.unissense.tech/public/unis_oa:$TAG \
-t docker.oa.unissense.tech/public/unis_oa:latest .
docker push docker.oa.unissense.tech/public/unis_oa:$TAG
docker push docker.oa.unissense.tech/public/unis_oa:latest
```
`OA_APP_BUILD` 不是运行时配置,它只在建前端产物那一刻用一次:把 tag 烤进包里,手机首页问候语
下面就会显示这一串数字(`frontend/src/utils/appBuild.ts`)。于是"这次发版到底生效没有"不必猜——
手机上那一串 == 下面这条命令里的 tag,就是生效了:
```bash
kubectl -n unis-oa get deploy/unis-oa -o jsonpath='{.spec.template.spec.containers[0].image}'
```
留空也能构建,那一串退回构建那一刻的时间戳,只是跟 tag 差个一两分钟,看着别扭。
集群拉不动镜像(内网 DNS 解析不到 Harbor)时才需要离线导入:
`docker save` → 拷到节点 → `ctr -n k8s.io images import unis_oa.tar`(K3S 自带 containerd,不用 `crictl`)。

View File

@ -152,6 +152,207 @@ spec:
containers:
- name: unis-oa
# 钉时间戳 tag:回滚才有得选。想用 latest 就把下面 imagePullPolicy 改成 Always
# 202611041447 起(已推 Harbor,digest sha256:21c627f3…,linux/amd64):手机上「表单内容」
# 那一屏能配了。前端 only,后端一行没动,下面那条 image 已升到这一版,集群重新导一次即生效。
# 原话:「表单内容里分费用报销基本信息、系统取数、完整单据,我就希望只有费用报销基本信息,
# 但里面展示哪些字段、怎么排放我需要有地方可以配置。」逐格那颗「手机上不展示」(上一版)
# 只能做减法——摆成什么样、先摆哪一格、明细摊不摊开仍然定不了,所以补的是**整表**那一层。
# 1) 表单设计器工具栏多一颗「手机端」(角标写此刻是「自动」还是「已配置」)。勾上
# 「按这份配置展示」,手机上就只出一节:节名、哪几格上屏、从上到下的顺序、每格的摆法
# (一行 / 整段 / 置顶大字 / 缩略图 / 只写数量 / 收成一行 / 逐条展开)在那张清单里一次配完,
# 两颗粒子改一格。清单上那颗「展示 / 不展示」写的还是格子上的 field.mobileHidden,
# 与属性面板那颗同一个键,不分两家存。排版件与「标签页」容器不进清单(手机上这一版只有一节,
# 段名由配置直接写,不再照它们认)。
# 「标签页」里那一整页**外部页面**也是一格(键是 `宿主格子key#页签key`):手机上不内嵌
# 别人的系统,摆一张「打开」卡片,点了新窗口看;它没有格子可以挂那颗逐格开关,
# 上不上屏因此记在这份配置的 fields[].hidden 上(全方案唯一的一个例外)。
# 2) 配置存在 oa_form.content.layout.mobile(与 layout.columns 同一层),**后端一行没动**:
# design.py:clean_formats 只按类型收字段上那几栏展现配置,layout 里的东西原样存回。
# 没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 3) 没勾这一档的表单走的还是原来那套按字段类型的自动归置(分节折叠、系统取数并一行、
# 末尾留「完整单据」),useFormPlan 那一条路一个字没改;环节字段权限、整单「默认隐藏」、
# 逐格「手机上不展示」、本环节要填那四道闸一道没少。「完整单据」按配置给不给,
# 不给时那条路收进顶栏「···」——要的是「只有一节」,不是「这一单在手机上看不全」。
# 4) 不往库里造测试数据:这份配置只躺在真被配过的那张表单上,升级不用动任何一行数据;
# 验收走 dev only 的预览台(preview-mobile.html?screen=detail&form=custom / &form=tabs 对照 /
# ?screen=panel),390 与桌面宽度都截过图,全程不打后端。
# 测试:新增 utils/mobileLayout.spec.ts 14 条、MobileLayoutPanel.spec.ts 11 条、
# FormDesignerView.mobile.spec.ts 6 条(含「配置存不存得住」「重开读不读得回来」
# 「改了算不算未保存、撤销退不退得回去」「删掉的格子不留死配置」),
# useFormPlan.spec.ts 加到 35 条,MobileFormSummary.spec.ts 加到 13 条,
# MobileWorkView.spec.ts 加到 14 条;全量 115 文件 / 1294 条绿,vue-tsc / eslint / vite build 干净。
# 口径与取舍见 docs/mobile-form-layout-config.md。
# 构建时把 backend/config.prod.toml 烤进镜像(21255 字节,含密钥),库里不用跑任何 DDL。
# 手机上现在这一串是 202611041447(首屏问候语旁 / 「我的」最末尾)。
# 202611041344 起:「终止」这件事终于能管住了。带三列 DDL
# (sql/upgrade/20261104_terminate_config.sql),镜像里 auto_create_schema=false
# 启动不补列,谁先跑错顺序,新后端读 oa_process 就报
# Unknown column 'oa_process.terminate_config'。
# 2026-11-04 核过生产库 unis_oa_prod:三列都已在,7 条流程的 terminate_config
# 全是 {}、归档行 operator 全空(都是「没配过」的默认口径),DDL 不必再跑一遍,
# 直接换镜像即可;重复跑会在第一句报 1060 Duplicate column name,是预期噪音。
# 起因是生产上那张 FYBX202611030017:审批记录里「部门主管」挂着红底一枚「终止」、
# 处理人写着主管本人、耗时 17 小时,看着像主管终止了自己的审批,实际是发起人
# 自己按的终止,而主管连待办都没打开过(view_time 为 NULL)。
# 1) 流程设计 → 流程信息 →「终止」(新列 oa_process.terminate_config):发起人终止
# 总开关 + 四个时间窗(always / 有人办过之后 / 走到指定环节之后 / 超过 N 小时)
# + 终止那一刻要调用哪几条写回模板。只管发起人,管理员与 /open/* 照旧。
# 开关关掉 = 「我发起的」「单据详情」「手机端菜单」三处根本不画这颗钮,
# 引擎同样拒绝;过了窗口则钮按不动、旁边写清为什么(判据只有 service/terminate.py 一处)。
# 2) 新增挂载时刻「流程终止时」(mapping.TRIGGER_TERMINATE):终止不是画布上的一环,
# 挂不到环节上,而三条终态的模板按绑定表单自动找齐——同表单的另一条流程会跟着发,
# 所以这一格配在流程自己身上。报文 event=terminated / event_key=terminate,
# 与模板自己勾终止那条是两个幂等键,两处都配就各发一条(设计器当场警告)。
# 3) 环节上那颗「允许终止」(config.allowTerminate) 从前是死配置:接口回显给前端
# 却没人读、引擎也不看。现在它是硬闸,单子正停在这一环且勾掉时发起人按不动。
# 4) 补上三个档案与通知的窟窿:归档行记下按终止的人(oa_task_completed 新列
# operator / operator_name,本人办的那些留空)、终止在流转日志旁挂一条 terminate
# 留痕(审批记录因此能写「由 X 终止」)、待办被清掉的人收到站内信(从前只有
# 发起人收到一句「流程已办结」,对方那条待办悄无声息变成点进去已归档的死链)。
# 终止原因在界面接口上改成必填,系统兜底那四个字不再冒充别人的意见。
# 5) 集成页两处可见性跟上:「什么时候真的会发」合并清单多一栏 terminateMounts、
# 配置体检多一类「终止挂载」,并修掉运行期不把停用模板挡下来那一处(界面承诺过不发)。
# 6) 级联终止(父单归档带走嵌入子单、撤回收回子单)明确不受这一格约束:真挡住
# 只会留一张父单已归档、子单还挂待办的孤儿单,而那两处是只记日志的。
# 顺带(不是本次需求,是这一片路上撞见的):标题预览不再把"规则自己上一轮写回这一格
# 的那句"当成办理人手写的,改规则引用的字段并开了自动重算时,保存前的预告终于说
# 「会变」了(backend/app/service/titles.py + scripts/check_intervention_title.py)。
# 测试:backend/scripts/check_terminate_control.py 58 项(全程内存 sqlite,一条语句
# 都不碰生产库),前端新增 6 份 spec 共 51 条 + 集成页两处 2 条,全量 112 文件 /
# 1237 条绿,vue-tsc / vite build 干净。
# 本条上线时手机上那一串是 202611041344,已被上面那一版接过去。
# 202611041007 起:手机端「完整单据」那一屏重做,外加两处配了却不起眼的口子。前端 only,后端一行没动。
# 1) 「手机上不展示」逐格开关(设计器里配)。原先这一屏是把桌面的 FormRenderer(readonly)
# 整个塞进下推层,手机上少摆哪几格全由代码说了算,配表的人只能看着单子猜。
# 现在属性面板「默认隐藏」旁边多了「手机上不展示」(field.mobileHidden):勾上之后
# 这一格在手机上摘要与「完整单据」里都不出现,而电脑 / 打印 / 导出 / 必填校验照旧。
# 画布上挂一枚「手机不展示」角标,那一屏顶部也写「有 N 格设了手机上不展示」。
# 框选一片还能一次收掉(多选面板上「手机上不展示 / 手机上都展示」两颗)——
# 那张报销单是 32 格,逐格点三十二下没人会去用。
# 「标签页」那一格不给这一档——手机版式的分节就是照它认的,批量那一档也跳过它。
# 这个键后端原样存回
# (design.py:clean_formats 只按类型收它认识的几栏),所以没有新列新索引。
# 2) 分节先认页签,再认分隔条。生产上那张费用报销单(v177,33 格)是靠一张「标签页」
# 分两页的:tab_1 费用报销基本信息(32 格)、tab_2 费用报销发票信息(整页嵌外部系统),
# 一条分隔条都没有。而 useFormPlan 原先只认 divider,于是三十几格全挤进一节「表单内容」,
# 段名一个字不见;页签本身走桌面 FormRenderer 那套按 12 列网格行号算的排法,
# 390 宽每格独占一行时行号全错配,几段的段头一起堆到最顶上——这就是
# 「页签为什么全在最顶上」那一句的根。现在两处都读同一份 utils/tabPages
# (tabsFieldOf/tabsOf/tabKeyOf/isEmbedTab),与桌面、后端一字不差,只是换成手机上
# 读得顺的摆法:页签在前、分隔条在后;压在「外部页面」那一页上的格子不摆(桌面上
# 本来也不显示),那一节整节给一张「打开」卡片,390 里不再嵌一整张 ERP 表。
# 新组件 components/oa/mobile/MobileFormReader.vue,待办详情与单据详情两屏共用;
# 一格一行、左问右答、空着也留一行(—),明细逐条只摆填了的那几列,签名直接把图画出来。
# 3) 没配核验闸门的单子不再摆「外部核验」那块面板。后端一直把 configured: bool(cfg)
# 发回来了(api/runtime.py:850 那段),是 ExternalCheckPanel 没认,于是没配这个功能的
# 流程也在单据上挂一块「外部核验 / 未提交 / 提交」。现在 configured=false 且没有历史结论
# 时整块不渲染(桌面手机一起修);真送过一次审的单照旧摆——闸门后来撤了,那句结论也得留着。
# 测试:新增 MobileFormReader.spec.ts 6 条、ExternalCheckPanel.spec.ts 3 条,
# useFormPlan.spec.ts 加到 20 条(页签分节 / 外部页面那页的格子不摆 / mobileHidden 单独计一笔 /
# readerSections 空值也留一行),FieldInspector.newTypes.spec.ts 加到 18 条(这一档勾得进字段、
# 「标签页」不给这一档而「默认隐藏」还在、排版件两档都没有、框选一次收一片),预览台加了 form=tabs
# (照生产那张分页 + 外部页面的报销单)与 open=reader,截过 390 的图;
# 全量 106 文件 / 1184 条绿,vue-tsc / eslint / vite build 干净。
# 手机上现在这一串是 202611041007(首屏问候语旁 / 「我的」最末尾)。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611040925 起:手机端详情页再收一遍——那一整块说明和「打印 / 刷新」两颗钮都不要了。前端 only。
# 红框那块(按第 13 版设计在走 / 费用报销流程 · FYBX202611030012 · 发起人:×(部门)/
# 发起时间:…)说的是「这张单怎么来的」,列表里刚读过一遍;手机上要答的是「现在怎么样了」。
# 于是两个详情页(/todo/:id 与 /work/:job)的抬头收成一行:左边几枚徽章,
# 右端一枚发起人标(部门只在 ≥640 那一档跟出来),再往下是关键数字。单号仍在审批记录末尾,
# 谁提的、什么时候提的就是那条时间线的第一行,信息一条没丢,只是不再占三排。
# 打印审批单手机上本来就不给(上一版撤的),这一版把「刷新」那颗按钮也撤了:
# 它挂在屏幕最上沿、离拇指最远,而手机上刷新本来就是一把手势。换成
# composables/useMobileRefresh.ts 两条道——
# · usePullToRefresh:只在页面已经滚到顶、手指还继续往下拖过 12px 才接管,阻尼 0.5、
# 上限 92px,越过阈值松手才刷;往上滑、弹层里滚、没到顶一律当场还给正常滚动,不抢
# preventDefault。触发时顶栏正中浮一枚「继续下拉 / 松开刷新 / 正在刷新…」的胶囊。
# 待办详情只认人主动下拉——那一屏有正在填的填写块,不能拿写了一半的字换一次「也许更新了」。
# · useRefreshOnReturn:只读那一屏没有输入框,从企微切回来(页面重新可见)自己取一次。
# 列表页与首页仍留那颗刷新按钮:那是几十条数据的入口,除了下拉还得给个显式的口子。
# 顺带把单据详情的吸底那一行改了规矩:只在真的办得动时才挂(提交发起 / 催办),
# 两条都不成立整条不挂——原先兜底那颗「刷新」既刷不出新东西,又永远压着正文最后两行;
# 流程干预 / 终止流程 / 看电脑版 / 字号全收进顶栏那个「···」。
# 测试:新增 useMobileRefresh.spec.ts 5 条,MobileWorkView.spec.ts 加到 11 条
# (整页没有「刷新」二字、办得动才挂吸底、下拉真的把 refresh 抛出去、给了取数那条路就等它取完),
# 全量 104 文件 / 1162 条绿;预览台 open=pull 截过 390 的图。
# 手机上现在这一串是 202611040925(首屏问候语旁 / 「我的」最末尾)。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611031836 起:手机上最后一块桌面版面——单据详情——也换过来了。前端 only,后端与接口零改动。
# 「部署了手机上还是老样子」这句质问这回的根子不在缓存、也不在 hub 那条跳转:构建号是新的、
# 顶部那条 44px 细栏也是新的,可正文还是桌面摆法。因为那一屏不是待办详情(/todo/:id),
# 是单据详情 /work/:job —— 已办 / 我发起的 / 待阅 / 首页通知弹层 / 流程监控点进来全是这一个
# 落点,而它从来没做过手机档:抬头四排说明 + 打印审批单/刷新/催办/终止流程 摊两排 +
# 「表单内容 / 流转流程图」+ 整屏表单 + 「基本信息 30 个格子」全摊开,划三屏看不到进度。
# WorkDetailView 现在按 phoneShell 分两档,手机那一档是 components/oa/mobile/MobileWorkView.vue:
# · 抬头两行(状态 / 当前环节 / 已挂起 / 当前处理人 + 发起人行)再往关键是几个关键数字;
# 流程名、单号、发起时间、「按第 N 版设计」都不再占第一屏,单号落在审批记录末尾。
# · 两页签:表单内容、审批记录(带条数)。桌面那张流程图画布不搬,换成同一条竖时间线;
# 这一屏没有待办要办,所以不给批注框,也不给打印审批单。
# · 吸底那一行只摆这一单真办得动的那一颗:提交发起 / 催办 / 刷新;流程干预(要 monitor:work)、
# 终止流程(要 can_terminate 且还在途)、看电脑版、字号三档收进「···」。终止与提交要写的
# 那句话也在手机上做成下推层,不弹桌面那个居中框。
# · 挂起、被第三方锁住、停在开始环节等提交,这三种「办不动」各在抬头下面说一句,按钮不哑着。
# /work/:job 也标了 meta.chromeless:手机那一档自己管顶栏和吸底,不再叠一条细栏、也不会被
# 底部标签栏压住最后两行;useChromeless() 要 chromeless 与 phoneShell 同时成立,
# 所以桌面的顶栏与 main 内边距一个字没动。判据仍由 WorkDetailView 一处算完递下去,
# 手机那一版自己不算一条;桌面那一版是同一个文件里的 <div v-else>。
# 测试:新增 MobileWorkView.spec.ts 10 条 + WorkDetailView.spec.ts 4 条,
# 全量 103 文件 / 1155 条绿;预览台加了 screen=work(&open=progress 直接到时间线),390 截过图。
# 手机上现在这一串是 202611031836(首屏问候语旁 / 「我的」最末尾)。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611031819 起:手机上那几屏接着收。前端 only,后端与接口零改动。
# 七件事,都是「390 的屏上不该出现的东西」:
# · 登录成功那句右上角提示在手机上不发(紧接着就是整屏换页,绿条只会盖住刚出来的列表);
# Toast 本身在手机上改成贴底居中一条,不摆关闭叉,桌面上两处照旧。
# · 顶部那条整栏(汉堡 + 站点名 + 通知 + 语言 + 深色 + 头像)手机上不挂了,它比正文还高。
# 子页面只留一行 44px 的细栏(components/layout/MobileTopBar.vue:返回 + 页名),
# 底部三格那几页连细栏都不要;通知、语言、深色、字号、退出、其余入口全收进「我的」。
# · 左侧那个抽屉在手机上整块不挂(AppSidebar v-if="!phoneShell")——它的拉手本来就是顶栏
# 那颗汉堡,顶栏没了它就是进不去的 DOM。768~1023 那一档汉堡与抽屉照旧,桌面一个字没动。
# · 「我的」那一格是新画的一屏(ProfileView.vue 手机档):身份 / 通知(未读数)/ 收款账户
# (还是那张表,走底部弹层)/ 按权限分组的入口 / 外观(深色 + 三档字号 + 语言)/ 加到主屏幕 /
# 退出,末尾钉着构建号。桌面那一版两张卡照原样。
# · 详情抬头砍到两行:徽章行 + 发起人行,再往下是关键数字。流程名在细栏上不再重复,
# 「单号 · 提交时间」「标题待更新」那两行和独立的发起人段并掉,单号落到审批记录末尾。
# · 表单内容一节最多摆六行(MobileFormSummary.vue 的 GROUP_ROWS),剩下的一按「展开更早 N 条」
# 才出来;明细本来就只占一行(12 条 · 合计),逐格读走「完整单据」。47 格的单子原先摊六屏,
# 现在第一屏答得完「这单大概是什么」,换一张单子不把上一张摊开的状态带过来。
# · 手机上更多操作里去掉「打印审批单」(手边没打印机,真要出纸回电脑上的详情页),
# /print/work/:job 那条路由与桌面那一档都留着。
# · 流转记录另画一条竖向时间线(components/oa/mobile/MobileFlow.vue),不再搬桌面那条:
# 默认只摆最近三步、发起那一行永远留着、意见两行读完、改单与附件各折成一行、
# 末尾高亮「停在谁手上」。数据仍出自 utils/approvalRecord.buildApprovalRecord,
# 与桌面同一份口径;桌面那条 ApprovalRecord 一字未动。
# 手机上现在这一串是 202611031819(首屏问候语旁 / 「我的」最末尾)。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611031727 起:修「手机上打开还是门户那一屏」。不是版式没发上去,是落地页挑错了。
# 生产上 139 个人挂在「普通员工」这个角色上,那一档有 work:todo、work:read,偏偏没有
# work:workbench —— 而手机上第一屏原先写死要先去 /workbench(那五张卡片),路由守卫再按
# 回退表把人送回 portal:home,于是这批人永远看见门户新闻页那一屏桌面版面,底部标签栏也只剩
# 待办/我的 两格(首页那一格按 work:workbench 过滤掉了)。看着就像「手机版式没做」。
# 现在 utils/returnPath.ts 的 landingPath() 按权限挑第一屏:手机上 工作台 → 待办 → 我的 → 门户,
# 桌面上门户照旧排第一。没有工作台的人直接落进待办那张卡片流(那是改造过的一屏)。
# 路由守卫的回退顺序、以及已登录又撞上 /login 时去哪一屏,都改成读这同一张表,不再各留一份。
# 要让那 139 个人也看见那五张卡片,不必改代码:权限角色里给「普通员工」勾上 work:workbench
# 就行,那是界面上的一次勾选,本版本没动任何权限数据。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611031703 起:手机端那套审批版式补全了,另把「这次到底发上去没有」写到了首屏上。
# 前端 only,后端零改动;判据只有屏幕宽度(<768,composables/useMobileShell.ts),
# 审批逻辑还是桌面那一份,权限、按钮能不能点、字段能不能编辑都不看宽度。
# · 落地页:手机上免登/登录的兜底页从门户 /home 换成 /workbench
# (utils/returnPath.ts 的 landingPath())。打开就看见那五张卡片,不用先翻过一屏新闻。
# · 首页:五张卡片 待办/已办/待阅/已阅/我发起的,一张对一个列表,数字就是那张列表的条数;
# 底部标签栏收成 首页/待办/我的 三格,「发起流程」搬到首页那五张底下的那颗钮。
# · 四张列表(待办/已办/待阅/我发起的)换成卡片流;待阅支持 ?tab=done,已阅就是它的第二档。
# 详情那一屏的竖屏版式是 202611030927 发的,这一版接着用它,没动判据。
# · 首屏问候语下面那 12 位数字 = 这次构建用的镜像 tag(构建时 --build-arg OA_APP_BUILD=$TAG)。
# 它跟 kubectl 里看到的 tag 对得上,就是真发上去了;对不上就只有两种可能:Pod 没换镜像,
# 或者这台手机被钉在电脑版(见下一条)。这玩意儿不靠配置开关,也不发请求,就是烤在产物里。
# · 更多操作里点过「看电脑版」的,现在底部标签栏头顶多一颗「看手机版」。原先那是条单行道:
# localStorage 里的 oa.mobile.desktop 一旦落下,手机上再没有切回来的入口,只能去清缓存——
# 「部署了却看不到变化」有一半是这么来的。
# 本版没有新列新索引,生产库不用跑 ensure_columns / ensure_indexes。
# 202611021707 起:「多选月份」不再一上来就平铺吃掉一整行,这一格长什么样交给配的人挑。
# 属性面板上多出「挑选方式」三档,用的是字段上已有的 pickerStyle(与设计器里那套同名同值):
# dropdown 下拉多选 = 默认,字段上不写东西——一只输入框样子的按钮,框里挂「2026年10-11月」
@ -589,7 +790,7 @@ spec:
# 「服务器内部错误,请稍后重试(编号 xxxxxxxx)」)
# 202610261047 起:镜像自带 backend/config.prod.toml(含密钥),且修了口令带 @ 时
# DSN 被撕成两个主机名的坑(backend/scripts/check_db_dsn.py 盯着)
image: docker.oa.unissense.tech/public/unis_oa:202611030927
image: docker.oa.unissense.tech/public/unis_oa:202611041447
imagePullPolicy: IfNotPresent
ports:
- name: http

File diff suppressed because it is too large Load Diff

View File

@ -207,7 +207,7 @@ seed 的「已存在就跳过」永远判不中,每轮启动都把同一批封
| `type` | 说明 | 关键 `config` |
| --- | --- | --- |
| `begin` | 开始,自动流转到下一环节 | `form`(可选,随流程默认表单) |
| `manual` | 人工审批,产生待办 | `mode` `taskValues` `taskScript` `first` `allowGoBack` `allowAddTask` `goBackConfig` `expireType` `expireValue` `emptyToCreator` `processingTaskOnceUnderSamePerson` `beforeArriveScript` `afterArriveScript` |
| `manual` | 人工审批,产生待办 | `mode` `taskValues` `taskScript` `first` `allowGoBack` `allowAddTask` `allowTerminate` `goBackConfig` `expireType` `expireValue` `emptyToCreator` `processingTaskOnceUnderSamePerson` `beforeArriveScript` `afterArriveScript` |
| `choice` | 条件分支,按路由表达式择一 | 无,逻辑在路由的 `expression` 上 |
| `parallel` | 并行网关,多路同时下发 | 无 |
| `merge` | 汇聚网关,等待前序全部到达 | 无 |
@ -286,6 +286,9 @@ seed 的「已存在就跳过」永远判不中,每轮启动都把同一批封
- `type`:`prev` 退回上一环节,`define` 退回 `data` 指定的环节
- `way`:`step` 逐步回退(回到被退回环节重新办理),`jump` 直接跳转
- `allowGoBack=false` 时前端不出现退回按钮,后端 `goback` 直接拒绝
- `allowTerminate` 管的是**发起人**那颗「终止」钮:单据正停在这一环时它为 `false`,界面不出现按钮、
引擎 `terminate` 同样拒绝(与 `allowGoBack` 一个待遇)。发起人能不能终止还有一层流程级的规矩
(开关 + 四个时间窗口 + 终止那一刻的写回),存 `oa_process.terminate_config`,见 README「流程终止」
- `GET /task/{id}/goback-targets` 给出当前可选的退回目标,回行带 `is_starter`
「退回发起人」不在 `goBackConfig` 的管辖之内:`type` 收窄的是能退回到哪几个**审批环节**,

View File

@ -0,0 +1,204 @@
# 费用报销:财务在第三方改了审定金额,怎么回写进 OA
对着你们生产写的。实况(2026-11-03 查 `unis_oa_prod`):
| 是什么 | 生产上的值 |
| --- | --- |
| 流程 | 费用报销流程 `91d42378cc0f49828e64eabfda2f010f`(已发布 v13) |
| 表单 | 费用报销单 `6b2ab85e3dd24a61be1efa3392c88288`(今天 10:09 刚加过字段) |
| 环节 | `cr_finance_manager`「财务经理」,OA 按钮已整环锁死,只有外部接口按得动 |
| 第三方应用 | `reimb`「财务数字助手」,scopes `task:read` + `task:write`(够用) |
| 现有调用 | `POST /open/nodes/locate` → `POST /open/nodes/{单号}/{环节id}/decide`,结论词 `AGREE` |
接口没变,就是你们**已经在调的那条 `decide`**,值放在报文的 `data` 里。要多做的只有一件事:
把 `cr_finance_manager` 的 `openApprove.fields` 从空数组改成那几格审定字段。设计理由见
[node-open-approve-design.md](node-open-approve-design.md),逐步报文见
[node-open-approve-examples.md](node-open-approve-examples.md)。
## 1. 生产上现在为什么写不进去
`decide` 的报文你们发得没问题,但 `oa_node_decision` 台账里每一条的 `data` 都是 `{}`。原因在
这一环的配置上:
```jsonc
// 生产现状:oa_activity.config(cr_finance_manager「财务经理」)
{
"openApprove": {
"enabled": true,
"apps": ["reimb"],
"confirm": "auto",
"decisions": { "AGREE": "agree", "REFUSE": "refuse" },
"routes": { "agree": "同意", "refuse": "驳回", "submit": "同意" },
"fields": [], // ← 空数组:表态能带的表单格子,一个都没放行
"opinion": { "agree": "财务数字助手已审核", "refuse": "财务数字助手已驳回" },
"note": "财务数字助手",
"lookup": ["processNo"],
"oaLock": { "enabled": true, "actions": ["handle","goBack","recall","addTask","transfer"] }
}
}
```
`filter_data` 在进引擎之前筛:`fields` 是空的,`data` 里再多的键也整个丢掉,**而且不报错**,
回包照样 `handled: true`。
好消息是第二道闸不用动:这一环的 `formPerms` 里**没有点名**那五个审定字段(它列的是
`sumTraffic`、`expenseTotal` 那批老字段),没点名的可填字段按默认档算,默认档是**可编辑**
(`formruntime.effective_perm`)。所以只改 `fields` 一处就够。
## 2. `data` 里就是表单字段名,这是这张单的可写性
| `key` | 界面上叫什么 | 类型 | 第三方能不能写 |
| --- | --- | --- | --- |
| `checkTraffic` | 审定市内交通费 | money | **能** |
| `checkEntertain` | 审定招待费用 | money | **能** |
| `checkTravel` | 审定差旅费用 | money | **能** |
| `checkTelecom` | 审定通讯费用 | money | **能** |
| `checkOther` | 审定其他费用 | money | **能** |
| `checkTotal` | 审定费用合计 | formula | 别交。公式 = 上面五项相加,服务端自己算 |
| `sumTraffic` `sumEntertain` `sumTravel` `sumTelecom` `sumOther` | 各类申请金额 | money + 公式 | 交不进,公式重算覆盖 |
| `expenseTotal` | 费用金额合计 | money + 公式 | 交不进,同上 |
| `offsetItems` | 冲销明细 | table,**挂了额度** | 交不进。挂额度 / 阈值的格子外部表态一律拒收 |
| `offsetTotal` | 冲销金额合计 | formula | 交不进 |
| `payMethod` | 收款方式 | select,字典 `oa_pay_method` | 能写,值只认 `cash` / `cheque` / `transfer` |
| `bankName` `payAccount` | 开户行名称 / 收款账号 | text | 能写,但这两格由取数带出(`_fetch`),别抢 |
| `applicant` `applyDept` `applyTime` `processNo` `title` | 申请人 / 部门 / 时间 / 单号 / 标题 | user / dept / auto / title | 交不进,系统格 |
| `accountProject` | 相关核算项目 | select,字典 `pms_project` | 能写,交字典里的 value |
| `reimbursement_date` | 报销月份(多选) | months | 先对口径再写:现网有 `"10"` 和 `"10月"` 两种存法 |
| `field_group*` `field_tabs` `cw_url` | 分组、标签页、助手链接 | group / tabs / url | 版面格没有值;`cw_url` 写了没意义 |
**只交改动的那几格。** 落库是浅合并,没交的格子一律不动;整份表单回传会把别人在你之后刚填的
格子按你那一刻的旧值盖回去。
## 3. 报文:照着发
### 3.1 改审定金额并通过(招待费那张)
生产在途单 `FYBX202611020014`,申请侧 `sumEntertain` 是 `1969.08`,财务审定 `1900`:
```http
POST {BASE}/open/nodes/FYBX202611020014/cr_finance_manager/decide
Authorization: Bearer {oat_…}
Content-Type: application/json
{
"result": "AGREE", // 环节认的词,翻成「同意」→ 走出线「同意」
"bizKey": "reimb-FYBX202611020014-fm", // 幂等键:同一趟重试只办一次
"opinion": "", // 省了走环节上的意见模板「财务数字助手已审核」
"data": {
"checkEntertain": 1900, // 审定招待费用
"checkTraffic": 0, // 审定市内交通费
"checkTravel": 0, // 审定差旅费用
"checkTelecom": 0, // 审定通讯费用
"checkOther": 0 // 审定其他费用
}
}
```
`checkTotal`「审定费用合计」由公式自动算成 `1900`,不用交也交不进去。
另一张 `FYBX202611020010`(申请侧 `sumTraffic` 755.96 / `sumTravel` 1155.64 / `sumTelecom` 200,
合计 2111.60)审定砍到 2000,就写成:
```jsonc
"data": { "checkTraffic": 700, "checkTravel": 1100, "checkTelecom": 200 }
```
金额写数字或数字字符串都行(`1900` / `"1900.00"`),别带千分位逗号、别带「元」;这一列
`precision` 是 2,落库存的是元为单位的数值。
### 3.2 驳回也照样能带值
`REFUSE` 翻成「驳回」,走出线「驳回」退回发起人,`data` 的规则一模一样。审定额想留在单子上给
发起人看为什么被驳,就一起交进来。
### 3.3 回包与落格
这一环是 `"confirm": "auto"`,第三方按下去当场以**财务经理本人**的身份走引擎那一步,字段权限、
必填、公式、额度、外部核验闸门一条不少:
```jsonc
{ "code": 0, "data": {
"handled": true, "route": "同意", "activity": "财务经理",
"status": "running", "done": false,
"work": { "job": "…", "serial": "FYBX202611020014", "status": "running" },
"tasks": [ { "id": "…", "activity": "财务总监", "identity": "…" } ],
"note": "已按环节「财务经理」的外部审批配置自动办理" } }
```
回包**不回**收下了哪几格,被白名单丢掉的那些键也不提示。接完自己验一次:
```bash
curl -s "{BASE}/open/works/{job}?with_data=1" -H "Authorization: Bearer {oat_…}"
```
对不上就是白名单没配好。查这一次表态办没办,拿同一个 `bizKey` 再发一次 `decide`,OA 原样回
第一次的结果(`alreadyHandled` / `alreadyStaged`),不会变成第二次表态。
要是想改成"第三方只备值,财务经理本人在 OA 点确认",把这一环的 `confirm` 换成 `"confirm"`:
回包变 `staged: true` + `decisionId`,值压在表态台账上(默认存一天),处理人走
`POST /task/{task_id}/node-decision/{decisionId}/confirm` 才真正落格并流转。
## 4. 意见里带上审定额(可选)
`openApprove.opinion.agree` 支持 `{serial}` 和 `{form.字段名}` 两个占位,想让它写进流转记录那句
带上审定额,改成:
```jsonc
"opinion": { "agree": "财务数字助手已审核,审定 {form.checkEntertain} 元" }
```
只认**这次报文里交上来的那几格**:`{form.checkEntertain}` 有值,`{form.checkTotal}` 取不到——
它是公式算出来的,不在报文里。
## 5. 在途的老单子有个前提
单据发起时冻结的是它那一刻那一版设计。`FYBX202611020010`(v11)、`FYBX202611020014`(v12)冻结的
那两版表单里**还没有审定这五个字段**,所以:
- 值写得进 `work.data`(表单里没定义的键原样保留),公式与条件分支也读得到;
- 但那张单的页面按冻结那一版渲染,**这几格在界面上不出现**,财务在 OA 里看不见自己审出多少;
- 今天之后新发起的单没这个问题。
老单要让人看见,只能退回重发起,或者用管理员那条口先补数据:`POST /api/v1/admin/work/{job}/data`
(登录态 + `monitor:work`,只交改动那几项,改动以「字段:旧值 → 新值」写进流转日志并知会当前
处理人与发起人)。**它不改公式**,`checkTotal` 要等下一环有人提交才算,别指望它把合计带出来。
## 6. 按 `reason` 分支,别比对中文
| `reason` | 什么意思 | 该怎么办 |
| --- | --- | --- |
| `NODE_WORK_NOT_FOUND` | 单号 OA 没认出来 | 核对 `processNo`;已归档的会另说一句 |
| `NODE_WORK_NOT_RUNNING` | 单据已办结 / 终止 / 作废归档 | 别再重试,读归档 `GET /open/works/{job}` |
| `NODE_WORK_AMBIGUOUS` | 同一个号撞上不止一张单 | 改报 job 号 |
| `NODE_TASK_AMBIGUOUS` | 这一环多条待办没点名 | 带上 `identity` |
| `NODE_NOT_PENDING` | 财务经理这一环还没轮到或已经过了 | 先 `locate` 问现在停在哪 |
| `EMBED_DECISION_UNKNOWN` / `EMBED_ROUTE_NOT_FOUND` | 结论词翻不出出口 | 现在认的是 `AGREE` / `REFUSE`,错误语会回这一环认得的词表 |
| `NODE_ROUTE_PIN_MISSING` | 钉的「同意」「驳回」出线在图上没了 | 重新配 `routes` |
| `403` | 这一环没对 `reimb` 开口,或应用没勾 `task:write` | 看 `apps` 名单与 scope |
| `400` | 引擎当场拒的:必填、额度超支、核验闸门没过 | 按 message 补数据 |
## 7. 落地清单
1. 设计器打开「费用报销流程」→「财务经理」→「外部审批」面板,**可写字段**加上
`checkTraffic` `checkEntertain` `checkTravel` `checkTelecom` `checkOther`。保存即生效——
`decide` 读的是 `oa_activity` 当前那一行;**重新发布**是让新单冻到带这份配置的快照上,
顺带跑一遍配置体检(结论词、钉空的出口会在这一步点名)。
2. 在途单不用退回重走(白名单读的是环节当前配置);只是老单页面上没有这几格,见 §5。
3. 第三方在报文里加 `data`,其余不动。`bizKey` 一单一次一个,别复用上一趟的。
4. 拿一张测试单跑通,用 `GET /open/works/{job}?with_data=1` 对一遍五个审定值 + `checkTotal`,
再翻单据的流转记录确认署名是「财务数字助手」。
5. 以后在设计器里重存「财务经理」的字段权限时要留意:一旦这五个审定字段被点名成
`readonly`,第 1 条的白名单就白配了,值会被引擎悄悄回滚成原值。
## 8. 顺带说清:另外几条也能带 data 的口
| 谁改、什么时候改 | 用哪条 | 碰不碰流转 |
| --- | --- | --- |
| 第三方在财务经理这一环给结论 + 改值(**本篇**) | `POST /open/nodes/{单号}/{环节id}/decide` | 碰 |
| 第三方持有那条待办,直接办 | `POST /open/tasks/{task_id}/execute` + `data` | 碰;没有 `fields` 白名单这道闸,靠待办归属 |
| 第三方只回值,不决定走不走 | 嵌页面 `POST /embed/callback`(`kind=prefill`) | 不碰 |
| 核验系统回结论(只写闸门配的快照格) | `POST /open/checks/report` | 不碰,闸门读 |
| 财务 / 管理员在 OA 里改在途单 | `POST /admin/work/{job}/data` | 不碰 |
| 发起人自己改 | `PATCH /job/{job}` | 不碰 |
已办结或终止归档的单子整行搬进 `oa_work_completed`,这几条全改不动。

View File

@ -0,0 +1,379 @@
# 手机端审批版式:只换版式,不换逻辑
对应场景:领导从企业微信里的卡片点开 → hub 免登 → OA 待办详情。原来的页面是照着 1440 宽的
桌面排的,同一套东西塞进 390 的屏上就成了一片挤在一起的小字加一条够不着的操作栏。
这一版只做一件事:**在手机上把单子读清楚、把「同意」按下去。**
落脚:`views/oa/{TaskDetailView,TodoListView}.vue` 的分叉、`components/oa/mobile/*`、
`composables/useMobileShell.ts`、路由上的 `meta.chromeless`、`components/layout/AppLayout.vue`。
**后端一行没动**,接口、字段、权限码、出口口径全部照原样。设计稿在 `design/mobile-approval.html`。
## 0. 为什么没有第二套逻辑
判据只有屏幕宽度,而且只允许出现在版式这一层:权限、出口怎么合并、必填闸、这一环哪几格改得动,
一律不看宽度。同一张单子在手机上能批,在电脑上就得同样能批,反过来也是。
所以手机版式自己不判断任何事。`TaskDetailView.vue` 仍是审批逻辑唯一的归属地,它把已经算好的那一份
(`routeButtons` / `requiredMissing` / `fieldPerms` / `goBackOptions` / 写回卡没卡 / OA 锁没锁……)
用 `provide(TASK_VIEW_KEY, …)` 交出去,`MobileTaskView.vue` 接过来只管两件事:把它摆成竖屏的样子、
决定「办完之后去哪儿」。接口写在 `components/oa/mobile/taskContext.ts`,缺一个属性 `vue-tsc` 就报错。
这一点是被教训逼出来的:早先那一版把桌面 `TaskDetailView` 里三百来行逻辑抄进了手机版,
抄过去的那一刻就落后了——表单里的附件没跟着提交、标题预告不显示、批注进不去、退回只有「逐级」、
加签只有「并行」、抄送没有「需处理」、写回卡住不提示,九处行为在手机上都和电脑上不一样。
现在的结构下,桌面每补一条判据,这一页自动跟着。
代价只有一处,写在桌面上:`submit` / `confirmGoBack` / `confirmPeople` / `confirmDecision`
多收一个可选的 `done` 回调。桌面不传,办完仍按老路子跳「已办」;手机版传的是「跳下一条待办」。
## 1. 三档判定,各管各的
| 判据 | 线 | 管什么 |
| --- | --- | --- |
| `useViewport` 的 NARROW | <1024 | 侧边栏收进抽屉、底部标签栏接手(平板也适用) |
| `PHONE_QUERY` | <768 | 要不要换成竖屏那套审批版式(`phoneShell`) |
| `meta.chromeless` + `phoneShell` | 两者都真 | 这一页把顶部栏和底部标签栏都让掉 |
两条线不能合成一条:拿 1024 去判版式,10 寸平板会被塞进只有单列的手机页,白瞎半屏。
`chromeless` 也要两条都真——桌面版式那条吸底操作栏是按「底下有条标签栏,我抬 3.5rem」摆的,
标签栏一没,它就凭空悬在半空。
还有一条退路:更多操作里那颗「看电脑版」把 `pinDesktop` 记进 localStorage。领导偶尔要看流程图、
要改别人填错的格子,钉上之后别再每次进来都赶他回手机版。
钉上得有法子下来。这一条原本是个单行道——全仓库只有「看电脑版」那一个写入点,没有解除的入口,
`oa.mobile.desktop` 一旦落下,`phoneShell` 从此恒假,只能去清缓存。现在底部标签栏在
`isPhone && desktopPinned` 时头顶多一颗「看手机版」(`MobileTabBar.vue`),点一下就回来。
底部那条只看屏幕宽度、不看这个开关,所以钉着的时候它照旧在场,正好把这句话摆在人看得见的地方。
## 2. 首页:五张小卡片,一张对一个列表
手机上打开 OA 落地的那一屏就是这一屏:`utils/returnPath.ts` 里的 `landingPath()` 先按设备挑表、
再按权限挑那一条真进得去的——手机上 **工作台 → 待办 → 我的 → 门户**,桌面上门户照旧排第一。
为什么要按权限挑:生产上 139 个人挂在「普通员工」那一档,有 `work:todo` 却没有 `work:workbench`,
写死落 `/workbench` 只会被路由守卫打回门户,而门户那一屏是桌面版面,看着就像手机版式没做。
这类人现在直接落进待办那张卡片流。门户没丢:抽屉侧栏里 `/home` 那一条还在。
`<768` 时 `/workbench` 换成
`components/oa/mobile/MobileHome.vue`:**待办、已办、待阅、已阅、我发起的**,五张卡片,
一张对一个列表,最后一张横着占满整行(2 列网格摆五张会留一个洞)。桌面上那四张统计卡 +
快捷发起 + 概览走 `v-else`,两版各摆各的,取数一处没动,后端零改动。
卡片按 `authStore.can` 过滤(`work:todo` / `work:done` / `work:read` / `work:created`),
判据与侧边栏、底部标签栏同一套:没那条权限的人不会看见一张点不进去的卡片。
「发起流程」也在这屏(`work:start` 才有),因为底部栏不再常驻那一格了。
**卡片上的数字与点进去那张列表同口径**,这在这个仓库里算 bug 级要求:
| 卡片 | 数字出处 | 为什么是它 |
| --- | --- | --- |
| 待办 | `appStore.todoCount` | 侧边栏与底部栏角标用的就是这一份(`/task/processing/count`) |
| 已办 | `statistics/workbench` 的 `completed` | 后端那条按 `DISTINCT work` 数,注释写明与已办列表同口径 |
| 待阅 | `appStore.readCount` | `/read/processing/count` 的 total 就是待阅列表的 total |
| 已阅 | `/read/completed` 的 total | 没有现成计数,只取一页一条拿那个数 |
| 我发起的 | `statistics/workbench` 的 `created_total` | `/work/created` 默认合并在办与已办结两张表,与它同口径 |
两个坑在这里记一下:工作台统计里的 `unread` 是**站内信未读**、不是待阅;
`month_completed` 是**全平台当月办结**、不是「我的已办」。都别拿去当卡片数字。
取数任一路挂了不弹红条,数字归零(跟角标那一套一个脾气:留旧数比没数更误事)。
底部标签栏从此只有三格:首页 / 待办 / 我的。
## 3. 列表:一屏四条,扫的是「哪条要先批」
`TodoListView.vue` 在手机上换成 `MobileCardList.vue`,数据还是 `useOAList` 那一份,它自己不取数。
首页那五张卡片点进去的另外四张列表(已办、待阅、已阅、我发起的)用的是同一个版式组件与同一个
`useMobileFeed`(把一页一页攒成下滑加载的那一段),差别只在「只看超时」那颗钮只有待办摆。
已阅就是待阅那张列表的 `?tab=done` 档位,切档位会把 `tab` 写回地址,刷新之后还停在原地。
一条卡片三行:标题、`发起人 · 部门 · 时间`、状态标签。左边一道色条表紧急(超时红、临期黄),
催办次数和出口数量挂在标签上。整条都是点击区,右边只留一个「去批」。
往下滑是攒页(IntersectionObserver 哨兵),不给分页器——手机上没人愿意去点「下一页」。
桌面上的搜索、状态筛选、批量审批都没进来:手机上一次就批几条,那几个控件加起来比单子还占地方。
## 4. 详情:一屏之内先答完四问
这一单是什么、谁提的、多少钱、卡在哪一步几号到期——抬头四问答完,才轮到内容。
**抬头就一行**:左边是那几枚徽章(`处理中` `总经理审批` `11/04 18:00` `催办 2`),
右端挂发起人(`李 李明`,部门只在宽一点屏上跟出来),再往下是关键数字那一档。
流程名在顶栏上,不再在抬头里重复一遍;`单号 · 提交时间` 那一行、`标题待更新` 那一行、
独立的发起人段落都并掉了——同一条信息在 390 的屏上出现两次,就是把下面真正要看的东西
推出第一屏。单号没丢,它落在审批记录那一条的末尾(见 §4.1),要查还能查到;
谁提的、什么时候提的,本来就是那条时间线的第一行。
**只有两个页签**:表单内容、审批记录。桌面上那张流程图画布在 390 的屏上缩成一团,
而「走到哪了、在等谁」时间线本来就说清楚了,手机上不再留画布。
**本环节要填的那几格提到最前面**。桌面上它们住在右栏处理面板里,手机上没有右栏,
读单子的路上顺手就填了。意见不在这里——那是按下「同意」之后的事。
**四十几格的表单不照抄网格**,按「判断这件事需要看什么」归置(`useFormPlan.ts`):
| 字段 | 手机上怎么摆 |
| --- | --- |
| 空值 | 不渲染,也不给占一行 |
| money | 最多两条上浮到抬头,先让人看到钱 |
| auto(系统取数) | 合并成一行折叠起来——发起人是谁、哪个部门,抬头已经有了 |
| table(明细) | 收成一行「明细 12 条 · 合计 7,181.00」,点开才是逐条 |
| attachment / image | 缩略图横滑,不占字段行 |
| tabs(标签页) | 那一页的名字就是分节标题;外部页面那一页整节换成一张「打开」卡片 |
| divider | 页里的第二段:段名跟在页签名后面(`费用报销基本信息 · 第二段`) |
| signature | 只在「完整单据」里看 |
明细点开是一条两行:第一行「第几条 · 花在什么上 · 多少钱」,第二行日子与备注。日期不当标题,
扫明细的人是先看这笔钱花在什么上的。四列摊成一条四行的话十二行就是两屏半,划完手都酸了。
**分节先认页签,再认分隔条**。原先这一层只认 `divider`,而生产上那张费用报销单是靠一张
「标签页」分两页的(`tabsMode: collapse`),于是三十几格全挤进一节「表单内容」,
段名一个字都不见——配表的人分好的两页,手机上等于没分。现在读的是同一份
`utils/tabPages`(`tabsFieldOf` / `tabsOf` / `tabKeyOf` / `isEmbedTab`),与桌面、与后端一字不差,
只是把「哪一页」搬到段名上:**页签在前、分隔条在后**,两者都没有才回落 `表单内容`。
压在「外部页面」那一页上的格子也不在摘要里出现——桌面上它们本来就不显示,
手机上跟着摆只会让人以为那一格丢了。
### 4.3 「完整单据」那一屏:手机上自己读,不借桌面的渲染
点开「完整单据」原先是把桌面的 `FormRenderer`(`readonly`)整个塞进下推层,两处跟不上:
- `FormRenderer` 的段头位置是按桌面 12 列网格的**行号**算的(`pagePlan` → `bandStyle(row)`)。
390 宽每格独占一行,行号全错配,几段的段头一起堆到最顶上——这就是
「手机端表单里的页签怎么全在最顶上」那一句的来处。页签本身在窄屏会塌成一排挤不下的按钮,
在弹窗里更没法用。
- 桌面的渲染**空值不占行**,可这一屏要答的偏偏是「这张单还少填了什么」。
现在换成 `components/oa/mobile/MobileFormReader.vue`:一格一行、左问右答、**空着也留一行**(`—`)、
按页签和分隔条分节且默认全开;附件摆缩略图、明细逐条只摆填了的那几列、签名直接把图画出来,
外部页面那一节给一张「打开」卡片而不是在 390 里嵌一整张 ERP 表。口径出自
`useFormPlan.readerSections()`,与摘要共用同一套分节判据。待办详情与单据详情两屏都读它。
**哪些格子上这一屏,现在能在设计器里逐格定**:属性面板「默认隐藏」旁边多了
「**手机上不展示**」(`field.mobileHidden`)。只影响手机版式——电脑、打印、导出、必填校验
一概照旧;「标签页」那一格不给这一档,因为段名就是照它认的。画布上会挂一枚
`手机不展示` 的角标,完整单据那一屏顶部也说清「有 N 格设了手机上不展示」。
框选一片还能一次收掉:多选面板上「**手机上不展示 / 手机上都展示**」两颗(排版件与「标签页」跳过)——
那张报销单是 32 格,逐格点三十二下等于没做。
这个键是新增的,后端 `design.py:clean_formats` 只按类型收掉它认识的几栏,原样存回,
**没动一行后端**。
**这一档后来被整表配置盖过一层**:逐格只能做减法(藏与不藏),摆成什么样、先摆哪一格、
明细摊不摊开仍然定不了。表单设计器工具栏上那颗「**手机端**」是把整张单在手机上摆成
**一节**的开关——节名、格子的顺序、每格的摆法一起配,存在 `content.layout.mobile`。
勾了「手机上不展示」的格子在那一版里照样不摆(同一个键,两处共用)。口径与取舍见
[mobile-form-layout-config.md](mobile-form-layout-config.md)。
### 4.4 没配闸门就不摆「外部核验」
`ExternalCheckPanel` 原先的判据是「接口通不通」,于是没配外部核验的流程也在单据上挂一块
「外部核验 / 未提交 / 提交」,点提交还被闸门当没这一回事。后端一直把
`configured: bool(cfg)` 发回来了(`api/runtime.py` 里那段),是这一层没认。
现在 `configured === false` 且没有历史结论时整块不渲染(桌面与手机一起修);
**真送过一次审的单照样摆**——闸门后来被撤了,那句结论也还得留在单据上给人看。
### 4.1 流转记录另画一条,不搬桌面那条
桌面那份 `ApprovalRecord`(408 行)带着内层滚动、编号、部门、耗时和一整个批注表单,
摊在 390 上比单子本身还长。手机上换成 `components/oa/mobile/MobileFlow.vue`:
竖着一条时间线,一步两行——谁在哪一步、什么时候,意见默认两行读完,
超过一句长话才给「展开」;改单折成「改了表单 · 2 项」,附件折成「附件 2」,点开才是原值新值与缩略图。
- **默认只摆最近三步**(`RECENT = 3`),更早的收成一颗「展开更早 N 条」。批十单的人只关心最近
那两步,第一次看这张单的人才需要全程;
- **发起那一行永远留着**,收掉开头就说不清这张单从哪儿来;
- **末尾那一行高亮说「此刻卡在谁手上」**(`停在「总经理审批」,等待 黄雪秋 处理`),
这一句才是审批人真正要的答案,桌面上它混在几十行记录里;
- 批注还挂在这条线上(`MobileSheet` + 桌面那份 `OpinionComposer` + `PeoplePicker`),不另开页签;
- **数据口径与桌面是同一份**:都出自 `utils/approvalRecord.buildApprovalRecord`,
两处不会各算一套记录。桌面那条一个字没动,仍给 `TaskDetailView` 用。
**吸底操作位**只三颗:`同意`(主按钮,永远在同一个位置,拇指不用找)、`退回`、`···`。
必填没填时主按钮换成一句「先填这几项:出差天数」,不给一颗点了报错的死按钮。
这一档是 chromeless 的:不挂顶部栏、不挂底部标签栏,`main` 也不留内边距,
两道常驻栏省下来的近 120px 全给单子本身,返回交给页面自己那颗返回键。
### 4.2 单据详情(`/work/:job`):只读那一屏也换成竖版
上面讲的待办详情(`/todo/:id`)是手上有活儿的人走的那条路。手机上还有另一批落点——
**已办 / 我发起的 / 待阅 / 首页通知弹层 / 流程监控**,以及发起之后那一跳,全都指向同一张单据
`/work/:job`(`WorkDetailView.vue`)。这一页原先只有桌面那一版,于是从「我发起的」点进来还是桌面那套:
抬头四排说明 + `打印审批单 / 刷新 / 催办 / 终止流程` 摊成两排 + 「表单内容 / 流转流程图」+
整屏表单 + 「费用报销基本信息 30 个格子」全摊开,划三屏还没看到进度。领导点开自己提的那张单,
看到的正是这一屏——这也是「手机版式不是没生效吗」这句质问真正的来处。
现在这一页也分两档(`components/oa/mobile/MobileWorkView.vue`,只读):
- **抬头就一行**:`处理中` `当前环节` `已挂起` `当前处理人:黄雪秋` 几枚徽章,发起人压成
同一行右端的一枚人标,再往下是关键数字那一档。桌面上红框那一整块——`按第 13 版设计在走`、
`费用报销流程 · FYBX202611030012 · 发起人:×(部门)`、`发起时间:…`——在手机上一个字都不摆:
那是「这张单是怎么来的」,列表里刚读过;这一屏要答的是「现在怎么样了」。单号仍在审批记录末尾,
谁提的、什么时候提的就是那条时间线的第一行。
- **两个页签**:表单内容、审批记录(带条数)。桌面上那张流程图画布不搬,换成 §4.1 那条竖时间线,
`can-comment` 不往下传,所以这一屏只有看、没有批注框。
- **吸底那一行只在真的办得动时才出现,而且就那一颗**:`can_start` → `提交发起`,否则
`canPress` → `催办`;两条都不成立整条不挂。原先兜底那颗 `刷新` 撤了——没得办的单子刷不出新东西,
而那条栏会一直压着正文最后两行。
- **低频那几件搬到顶栏的 `···`**:`流程干预`(要 `monitor:work`)、`终止流程`(要 `can_terminate`
且还在途)、`看电脑版`、三档字号。屏幕下沿只留给「此刻要按的那一颗」。
- **终止与提交要写的那一句话也在手机上做成下推层**,不弹桌面那个居中框。
- **这一屏没有的**:打印审批单、意见框与那套提交/退回出口(没有待办要办)、桌面那三排抬头说明。
- 挂起、被第三方锁住、停在开始环节等提交,这三种「办不动」各在抬头下面说一句,别让按钮哑着。
判据仍旧由 `WorkDetailView` 一处算完递下去(`canPress` / `canIntervene` / `startLocked` /
`beginDecisions`),手机那一版自己一条都不算,不会出现「电脑上能终止、手机上说不行」。桌面那一版
是同一个文件里的 `<div v-else>`,一个字没动,包括打印、流程图画布和右栏那三张卡片;
两个要写意见的确认框从桌面块里挪到了两条版式外面共用,`BaseDialog` 本来就被送到 `body`,
挪位置不动样式,只是确认那颗改成显式传词(`confirmTerminate(terminateOpinion)`),
免得手机上抛上来的那句意见被当成点击事件。
`/work/:job` 也标了 `meta.chromeless`:手机上这一屏自己管顶部那一行和吸底那一行,
不再叠一条 `MobileTopBar`,也不会被底部标签栏压住最后两行。桌面不受这条影响——
`useChromeless()` 要 `meta.chromeless` 与 `phoneShell` 同时成立才算数。
## 5. 动作一律 bottom sheet,不用居中弹窗
`BaseDialog` 居中、宽度按内容撑,那套尺寸在 375 的屏上会把「确定」顶到屏幕外。
审批动作的弹层都只需要「填一点东西 + 一颗主按钮」,从屏幕下沿推上来之后主按钮位置固定,
而且躲开了企业微信自带的顶部标题栏。
- 多出口先选一条再写意见,**每条出口上写着它去哪儿**(`同意 → 财务复核`),不用点了才知道;
适用条件不成立的那几条当场标黄说为什么走不了(手机上没有悬停,等人次点完再吃一句提示是白费一次拇指),
点了也带不走——挡回来的是桌面那份 `pickRoute`,手机版式没有第二条闸;
- 同意那一屏只有「说一句 + 提交」:五句常用意见点一下就填进框,主按钮是「提交,看下一条」——
手上通常不止一条,办完不停在原地;
- 退回带目标环节 + 逐级/直退 + 意见,加签带前后/并行串行,抄送带要不要对方处理,
与桌面那几个弹窗的选项一一对上,一样不少;
- 更多操作:加签、转办、抄送、分享、完整单据、看电脑版,末尾三档字号。手机上不给「打印审批单」
这一档——手边没有打印机,真要出纸是回电脑上的详情页做的事,`/print/work/:job` 那条路由留着不动;
(字号靠 `html` 的 `font-size` 整体缩放,Tailwind 的字号间距都是 rem,一处改完全屏跟着走)。
**「完整单据」是那条兜底的路**:折叠了多少格、哪些是空值、签名长什么样,进去一个字段都不会少,
用的是桌面那套只读渲染,只把行距收一档。摘要负责好读,这一份负责不漏。
### 5.1 刷新不是按钮:下拉这一把,加上回到前台补一次
两个详情页原先都在顶栏右侧摆一颗刷新图标。那是全场离拇指最远的一次点击——它在屏幕最上沿,
而拇指天然落在下半屏;手机上有一把手势专门干这件事,就是往下拉。于是按钮撤了,
换成 `composables/useMobileRefresh.ts` 两条道:
- **`usePullToRefresh`**:只在页面已经滚到顶、手指又继续往下拖过 12px 才接管,拖过阈值才算数,
阻尼 0.5、上限 92px;往上滑、在弹层里滚、页面还没到顶,一律当场把手势还给正常滚动(不抢
`preventDefault`)。触发时顶栏正中浮出「继续下拉 / 松开刷新 / 正在刷新…」那枚胶囊,松手即散。
待办详情**只有**人主动下拉才取——那一屏有正在填的填写块,不能拿人家写了一半的字去换一次「也许更新了」。
- **`useRefreshOnReturn`**:企微里点开单子、切回去聊两句、再切回来,这中间单子早被人批掉一环了。
只读那一屏(`/work/:job`)没有输入框,回到前台就自己取一次,不会吃掉谁写的东西。
列表页与首页仍留着那颗刷新按钮:那是几十条数据的入口,下拉之外还得给个显式的口子;
详情页不一样,它进门就取过一遍,之后只有「别人动了这张单」这一种变化。
## 6. 常驻栏:手机上只留一条细栏和一条标签栏
截图里那条顶栏(汉堡 + 站点名 + 通知 + 语言 + 深色 + 头像)在 390 上比正文还高,整条不要了
(`AppLayout.vue`:`<AppHeader v-if="!chromeless && !phoneShell" />`)。桌面上一个字没变。
那几件事各有各的去处,没有一件是丢掉的:
| 原来在顶栏 | 手机上在 |
| --- | --- |
| 页名 | 子页面上那条 44px 细栏(`MobileTopBar.vue`,只有返回 + 页名) |
| 通知(铃铛 + 未读) | 首页抬头那颗铃铛 与 「我的」那一行,都开同一张底部弹层 |
| 语言 / 深色 / 字号 | 「我的」→ 外观 |
| 头像菜单(退出、说明、看电脑版) | 「我的」 |
| 抽屉菜单(其余入口) | 「我的」→ 按权限过滤的那几组入口 |
| 「有新版本」那颗钮 | 首页下面一条横贯的细条(`data-test="m-update"`) |
细栏也不挂在底部三格常驻的那几页(`/workbench` `/todo` `/profile`)——它们本来就在导航上,
再顶一行标题只把正文往下推。详情页连细栏也不要,自己管那一行(`meta.chromeless`)。
**左侧那个抽屉在手机上整块不挂**(`<AppSidebar v-if="!phoneShell" />`)。它的拉手本来就是顶栏那颗
汉堡,顶栏没了,抽屉就成了一堆进不去的 DOM;入口改由「我的」那一屏按权限分组给出。
768~1023 那一档(平板、企微 PC 端缩小窗口)照旧:汉堡在,抽屉也在,桌面上一个字没动。
**「我的」这一格是这次新加的一屏**(`ProfileView.vue` 手机档):身份一行、通知一行、收款账户
(点开还是那张表,字段与桌面同一份)、按权限过滤的入口若干组、外观(深色开关 + 三档字号 + 语言)、
添加到主屏幕、退出登录,末尾钉着构建号。桌面上那一版(资料卡 + 收款账户两张卡)照原样。
**提示也收干净**:`Toast` 在手机上贴底居中一条(`inset-x-3 bottom-20`,抬过标签栏,也不压
详情页那张吸底操作栏),不摆关闭叉,只走 `translate-y` 进出;登录成功那一句在手机上不发——
紧接着就是整屏换页,那条绿横幅只会盖在刚出来的列表上。桌面上两处都照旧。
## 7. 怎么看效果、怎么验
### 7.1 线上:手机上那一串数字就是镜像 tag
版式改动最难自查的一点是「发上去了没有」。首屏问候语下面钉了一串 12 位数字
(`utils/appBuild.ts` 的 `APP_BUILD`,`MobileHome.vue` 里 `data-test="m-build"`),它是打包那一刻
由 vite 注入的构建号,构建时把镜像 tag 递给它,两边就是同一个值:
```bash
TAG=$(date +%Y%m%d%H%M)
docker buildx build --platform linux/amd64 --load --build-arg OA_APP_BUILD=$TAG \
-t docker.oa.unissense.tech/public/unis_oa:$TAG .
kubectl -n unis-oa set image deploy/unis-oa unis-oa=docker.oa.unissense.tech/public/unis_oa:$TAG
```
手机上看到 `202611031703`,集群里那个 Pod 跑的也是 `:202611031703`,两句话就把「生效」说完了。
数字对不上只有三种可能,按概率排:
1. **Pod 还是旧镜像**。`imagePullPolicy: IfNotPresent`,`latest` 不会重拉,所以只能用时间戳 tag 换。
`kubectl -n unis-oa get pods -o jsonpath='{.items[*].status.containerStatuses[*].imageID}'` 当场验。
2. **这台手机被钉在电脑版**。清掉 `oa.mobile.desktop`,或者用新加的「看手机版」那颗钮。
3. **屏幕宽度不够窄**。闸门是 `<768`,企微 PC 端和 10 寸平板拿到的仍是桌面版式,这是设计如此。
数字对得上、可这一屏还是桌面摆法,那就不是发没发上去的问题,是**这一屏本来就没做过手机档**——
`/work/:job` 就是这么漏过一次的(构建号是新的,顶部细栏也是新的,正文却还是桌面那套四排抬头,
见 §4.2)。所以别只盯构建号:那一屏归哪个组件管,先去 `router/index.ts` 对一眼。
`index.html` 后端发的是 `Cache-Control: no-cache`,`/assets/*` 带哈希又标 `immutable`,
换版本等于换 URL;离线外壳对导航请求走网络优先。所以缓存基本不是嫌疑人,别拿清缓存当第一招。
### 7.2 本地:预览台
版式这东西看代码看不出来,得真摆到 390 的屏上。`frontend/preview-mobile.html` 是预览台:
挂真的手机版式组件、吃真的 Tailwind、走真的词条,数据用 `mobileFixtures.ts` 里那张照真实报销单
抄的假单子(两分隔条三节、四十七格里一多半是空的、明细十二行、发票两张、这一环还要补两点)。
没有后端、没有登录也能把每一屏截下来对一遍,所以它只在 dev 下存在,不进产物。
```bash
cd frontend && pnpm dev
# http://localhost:3000/preview-mobile.html?screen=home
# http://localhost:3000/preview-mobile.html?screen=list
# http://localhost:3000/preview-mobile.html?screen=detail&open=approve
# http://localhost:3000/preview-mobile.html?screen=work&open=progress
# http://localhost:3000/preview-mobile.html?screen=profile
# http://localhost:3000/preview-mobile.html?screen=work&form=tabs&open=reader
```
`screen` 可选 `home` `list` `detail` `work` `profile`(`work` 就是 §4.2 那一屏);`open` 可选 `routes` `approve` `menu` `people`
`goback` `rows` `reader` `progress` `missing` `frozen` `readonly` `notice` `bank` `dark`,
`scroll=520` 直接滚到指定位置(弹层里那一屏自己滚,`window` 滚不动它),`blocked=1` 把「退回修改」那条出口的适用条件设成不成立,
看走不通的出口怎么交代。
`form=tabs` 把那张假单子换成生产上费用报销单的形状——一张「标签页」分两页、第二页整页是外部系统、
其中一格勾了「手机上不展示」。**分节、外部页面那一节、逐格开关这三件事,只有在这种表上才看得出对不对**,
默认的 `mobileFixtures` 那张只有分隔条,替不了它。
截屏注意:headless Chrome 把窗口宽度钳在 500,量不到真机的 390,要么套一层定宽 iframe,
要么用 CDP 的 `Emulation.setDeviceMetricsOverride`。另外 `--virtual-time-budget` 不推合成器,
弹层那 260ms 的位移会被拍成「划到一半」,看着像版式错了,其实是快门按早了——真等一秒再截。
自动化那一头:`MobileTaskView.spec.ts`(12 条)盯的是「什么摆在哪儿」,包括必填没填时不给点同意、
两条出口要先挑一条、走不通的出口当场说为什么且点不走、意见 chips 真能填进框、
提交整个交给桌面那份逻辑、不归他办时操作位不说谎;`useFormPlan.spec.ts`(20 条)盯归置口径,含页签分节、外部页面那一页的格子不摆、`mobileHidden` 单独计一笔,
以及 `readerSections` 那套「空值也留一行」的读法;`MobileFormReader.spec.ts`(6 条)盯 §4.3 那一屏:
按页签分节、外部页面给卡片并带上 `标签页key#页签key` 那个回写分区键、手机上不展示的那格哪儿都不出现还要报数、
空值留一行破折号、环节权限藏起来的不出现。`ExternalCheckPanel.spec.ts`(3 条)盯 §4.4 那三条:
没配闸门不摆、配了就摆、闸门撤了但有结论仍然摆。设计器那一档由
`FieldInspector.newTypes.spec.ts`(18 条)里那四条盯:普通格子有「手机上不展示」且勾得进字段、
「标签页」那一格不给这一档而「默认隐藏」还在、排版件两档都没有、框选一次收一片而排版件不参与。
`MobileFormSummary.spec.ts`(4 条)盯「一节最多六行、剩下收成一颗『展开更早 N 条』、换一张单子不把上一张摊开的状态带过来」;`MobileFlow.spec.ts`(5 条)盯这条时间线的三条底线:默认只有最近三步、发起那一行不许被收掉、「等谁处理」和单号还在;`MobileTopBar.spec.ts`(3 条)盯那条细栏只写页名与返回;`AppLayout.spec.ts`(6 条)里四条盯的就是「手机上整条顶栏不挂、抽屉不挂、细栏只挂在子页面、桌面照旧」;`MobileHome.spec.ts`(8 条)盯五张卡片的顺序、地址、权限过滤,以及上面那张口径表——数字来源写死在断言里,谁换成自己另算一份就红,另有一条盯抬头那颗铃铛与它那张弹层;`MobileTabBar.spec.ts`(5 条)盯底部栏只有三格、以及钉在电脑版时那口回去的井;`useMobileFeed.spec.ts`(5 条)盯攒页不重不漏、回第 1 页清干净;`ReadListView.spec.ts`(3 条)盯 `?tab=done` 落地就在已阅、切档位把档位写回地址。
`MobileWorkView.spec.ts`(12 条)盯 §4.2 那一屏:抬头不重复流程名与发起时间、整页没有「刷新」也没有
打印审批单、没有画布、切页签才出时间线且单号在末尾、办得动才挂吸底那一行、终止走下推层并把意见抛出去、
没权限时 `···` 里不摆那两颗、挂起与被锁各自说一句,还有一条盯下拉这一把真的把 refresh 抛出去、给了取数那条路就走它且胶囊等到取完;
`useMobileRefresh.spec.ts`(5 条)盯手势本身——越过阈值才刷、没到顶或往上滑就让位、禁用时不抢
`preventDefault`、卸载后不再监听、回到前台补取一次;`WorkDetailView.spec.ts`(4 条)盯那个岔口本身——
手机上整页换掉且判据原样递下去、电脑宽度一格都没少。
`returnPath.spec.ts`(6 条)盯手机上落地那一屏:有工作台落那五张卡片、没有工作台落待办、桌面落门户、
站外地址不被带出去——它原先写死落 `/home`,而且没有 `work:workbench` 的人会被守卫打回门户新闻页。
全量 `npx vitest run` 1184 条绿,`npx vue-tsc --noEmit` 与 eslint 干净,`vite build` 通过
(预览台两个 html 不在产物里:rollup 只有一个入口 `index.html`)。真机那几件(企微内置浏览器、iOS 安全区、软键盘顶页面)还得在手机上过一遍。

View File

@ -0,0 +1,190 @@
# 手机端表单版式:手机上只出一节,摆哪几格、怎么摆能配
原话是这一句:**「手机端的流程详情里面表单内容里面分:费用报销基本信息、系统取数、完整单据。
我不希望这样,我就希望只有费用报销基本信息。但是费用报销基本信息里面展示哪些字段、怎么排放
我需要有地方可以配置。」**
这份文档写的是这一档怎么落的:配置长什么样、存在哪儿、手机上怎么读、哪些东西**一个字没动**、
怎么验。**不往库里造测试数据**——一张表单上的几个键而已,配在真实表单上就行。
## 0. 一页看完
| 要做的事 | 配在哪儿 | 生效范围 |
| --- | --- | --- |
| 手机上那一屏只出一节 | 表单设计器 → 工具栏「**手机端**」→ 勾「按这份配置展示」 | 只影响手机版式(待办详情 + 单据详情) |
| 那一节叫什么 | 同一面板 → 「这一节的名字」(留空取第一个页签名,再没有写「表单内容」) | 同上 |
| 摆哪几格、什么顺序 | 同一面板 → 那张清单,从上到下就是手机上从上到下,两颗粒子改一格 | 同上 |
| 某一格上不上屏 | 清单上那颗「展示 / 不展示」,或属性面板那颗「**手机上不展示**」(**同一个键**) | 同上 |
| 那一格怎么摆(一行 / 整段 / 置顶 / 缩略图 / 收成一行 / 逐条展开) | 清单上那一格右侧的下拉(可选项按字段类型给,选不出摆不出来的组合) | 同上 |
| 「标签页」里那一整页**外部页面**要不要给一张「打开」卡片 | 同一面板 → 清单里那一行的「展示 / 不展示」(那颗开关记在这份配置里,属性面板上没这一颗) | 同上 |
| 末尾还要不要「完整单据」那一屏 | 同一面板 → 「末尾留『完整单据』入口」(默认**不留**) | 待办那一屏的 `···` 里始终有这条路 |
| 配到一半想退回自动归置 | 把开关关掉即可,配好的顺序留在配置里 | — |
三条贯穿全文的分寸:
* **不开这一档就等于不存在**。没配过的表单走的还是原来那套按字段类型的自动归置,
判据在 `components/oa/mobile/useFormPlan.ts`,那一段代码这条路一行没改。
* **配置只管"摆不摆、怎么摆",不管"能不能看"**。环节字段权限、整单「默认隐藏」、
逐格「手机上不展示」、本环节要人填的那几格,这四道闸一道没少(见 §4)。
* **后端一行没动**。这份配置住在 `oa_form.content.layout.mobile` 里,
`api/design.py:clean_formats` 只按类型收字段上那几栏展现配置,`layout` 里的东西原样存回。
## 1. 那份配置长什么样
```jsonc
// oa_form.content
{
"fields": [ /* 桌面那张 12 列表,一个键都没多 */ ],
"layout": {
"columns": 12,
"grid": 12,
"mobile": {
"enabled": true,
"title": "费用报销基本信息",
"showFullSheet": false,
"fields": [
{ "key": "reason", "style": "block", "label": "事由" },
{ "key": "amount", "style": "float" },
{ "key": "days" },
{ "key": "rows", "style": "list" },
{ "key": "invoices", "style": "gallery" },
// 外部页面那一格的键带着页签:宿主格子key#页签key
{ "key": "tabs_host#tab_2", "style": "embed" }
]
}
}
}
```
类型定义:`frontend/src/types/index.ts` 的 `MobileLayout` / `MobileFieldLayout` / `MobileFieldStyle`。
**为什么存在 `layout` 而不是新开一张表**:它和 `layout.columns`、`layout.label_width`
是同一层东西——只讲"这一张表怎么摆",不参与流转、不参与校验、不参与权限。存成一张表
要么加一次迁移、要么加一次 join,换来的只是把一件事说两遍。**为什么整份存而不是散在字段上**:
要配的是**顺序**,顺序是格子之间的事;散在 32 个格子上就得给每格存一个序号,
挪一格要改一片,还会漂(删一格后面的序号全乱)。
**某一格上不上屏不在这里**,它写的还是格子上的 `mobileHidden`——那颗键在属性面板里已经存在了
(见 [mobile-approval-layout.md](mobile-approval-layout.md) §4.3),面板上那颗"展示 / 不展示"
改的就是它。两份开关早晚会变成"属性面板勾了、手机端面板没勾"。
`style` 的可选项由字段类型给(`utils/mobileLayout.ts:styleOptionsFor`):文本类 `row` / `block`,
数字金额多一档 `float`,附件与图片 `gallery` / `count`,明细 `card` / `list`,签名只有一档。
配置里写了这一档新类型吃不下去(换了类型、从别的表单粘过来),`styleFor` 回落到该类型的默认档,
不会摆出一个空白的格子。
## 2. 手机上怎么读这一份
`utils/mobileLayout.ts` 是这一层的口径(读配置、排序、挑摆法、对账),
`components/oa/mobile/useFormPlan.ts:planForm` 在最开头分岔:
```ts
const mobile = mobileLayoutOf(schema) // 只有 enabled 为真才回一份,否则 null
if (mobile) return planByMobileLayout(mobile)
// 下面那套自动归置原封不动
```
开了这一档之后出来的是:一节(`groups[0]`)、`auto` / `media` / `signature` 三个桶全空、
`custom: true`、`showFull` 照配置。`MobileFormSummary.vue` 认 `plan.custom` 走另一段模板,
按 `groups[0].items` 的顺序逐格摆,每格照自己的 `kind` + `style` 渲染。三处与自动归置那版不一样:
| | 自动归置 | 按配置摆 |
| --- | --- | --- |
| 系统取数那几格 | 并成一行「系统取数 6 项」,折叠 | 配了它就是这一节里的一格,跟别的格平起平坐 |
| 空着的格子 | 不渲染,只报"折了几个空的" | **照样摆**,右边一个 `—` |
| 一节里超过六行 | 折起来,按一颗「展开更早 N 条」 | 不折:点名要的格子不该再被收起来 |
| 明细 / 附件 / 签名 | 各归各的桶,位置不由格子说了算 | 跟着格子自己的位置摆在这一节里 |
| 末尾「完整单据」 | 永远有 | 配置说了算 |
**空值为什么改成照样摆**:这一屏要答的是"我要看的这几格填了没有"。配表的人点了名,
格子却因为没值自己消失,他就得先猜"是没填,还是被我配丢了"。摘要那版反过来——
四十几格里挑能看的,空的不占行。两处口径不一样是各自要答的问题不一样,不是漂移。
**「置顶」那几格不住在这一节里**:它摆到抬头那一排大字(`plan.floats`,`MOBILE_FLOAT_MAX = 3`),
超出三格的回到节里按顺序摆,不丢。抬头本来就在讲"这单大概是什么",摆四五个数就成了报表。
**配了却没写到的格子排在后面**,不是不摆。配完之后又往表单上加格子是常事,
这时候新格子该出现——凭空消失是那种要查半天的错。设计器每次开门都按现在的表把清单重算一遍
(`pruneMobileLayout`:删掉的收掉、新加的补在最后),所以清单和表单永远对得上。
**「标签页」里那一整页外部页面也算一格**(`mobileCells` 把它合成出来,键是 `宿主格子key#页签key`)。
手机上不内嵌别人的系统,摆的是一张「打开」卡片,点了新窗口看——与「完整单据」那一屏同一个口径
(390px 里嵌一整张 ERP 表等于没法看)。它没有格子可以挂「手机上不展示」,那颗开关因此记在
这份配置的 `fields[].hidden` 上,是整个方案里唯一的一个例外。
压在它那一页上的普通格子照样能配:桌面上那几个值藏在别人的页面里,手机上反而可以单独摆出来看。
## 3. 设计器那一侧
入口在表单设计器工具栏:「**手机端**」,旁边一枚角标写着此刻是「自动」还是「已配置」。
面板是 `components/oa/design/MobileLayoutPanel.vue`。
**为什么做成一张清单而不是往属性面板里再塞几栏**:属性面板一次只看一格,
而顺序是格子之间的事——摊在 32 个属性面板里没人能看出整张单子在手机上读起来是什么样。
清单从上往下就是手机上从上往下。
**改动当场交回画布**,面板上没有"确定"这一步(只有一颗「关闭」)。因此撤销栈与
「未保存」那颗黄点必须认这份配置:`FormDesignerView.vue` 的签名从"格子 + 整表设置"
扩成"格子 + 整表设置 + 手机端那份"。这一条是补回来的——原先 `extras` 不在签名里,
排完一版顺序关掉弹窗,画布看着什么都没发生,保存按钮也不亮,配的东西静悄悄就丢了
(`FormDesignerView.mobile.spec.ts` 里有一条专门钉这个)。
排版件(分隔条、说明、空白、隐藏、标题)与「标签页」容器本身不进清单:前者没有值,
摆上去只是一行空白;后者是个壳,进去的是它那一页一页的内容——外部页面那几页会以
「外部页面」这一类出现在清单里,名字取页签名,摆法只有「打开卡片」一档。
## 4. 四道闸一道没少
配置排在最前面的是"这张表想让人看什么",不是"这一环能看什么"。下面四条优先级不变:
1. **环节字段权限 `hidden`**:那一环不让看的格子,配了也不上屏(`perms[field.key] === 'hidden'`);
2. **整单「默认隐藏」**(`field.hidden`):连桌面都不摆,手机上更不摆;
3. **逐格「手机上不展示」**(`field.mobileHidden`):清单上那颗"不展示"写的就是它,
记在 `plan.hiddenMobile`,与环节藏起来的 `plan.dropped` 分两笔算;
4. **本环节要人填的那几格**(`needKeys`):由这一屏顶上那个「本环节要填」的填写块负责,
摘要里不重复出现——两版都一样。
那一页外部页面还多一档:环节把整个「标签页」那一格藏了,或者只藏了那一页
(`formPerms` 里那个 `标签页格子key#页签key`),卡片都不摆,记进 `plan.dropped`。
「完整单据」那一屏(`MobileFormReader.vue`)没改:它要答的是"这张单还少填了什么",
所以照旧一格一行、空值也留、按页签与分隔条分节。把它的入口从摘要末尾撤掉之后,
单据详情那一屏(`MobileWorkView.vue`)原本就没第二条路了,于是那条入口收进顶栏的 `···`
——**要的是"只有一节",不是"这一单在手机上看不全"**。待办那一屏的 `···` 本来就有这一条。
## 5. 验收
不改代码就能看的两条:
```bash
cd frontend && pnpm dev
# 配过的样子:http://localhost:3000/preview-mobile.html?screen=detail&form=custom
# 没配的样子(对照):http://localhost:3000/preview-mobile.html?screen=detail&form=tabs
# 面板本身:http://localhost:3000/preview-mobile.html?screen=panel
```
预览台是 dev only 的(`src/dev/mobilePreview.ts`),吃真的版式组件、真的词条、真的 Tailwind,
数据用 `mobileFixtures.ts` 那份假报销单——**不打后端、不碰数据库**。
测试(`cd frontend && npx vitest run`,全套 1294 条):
| 文件 | 盯什么 |
| --- | --- |
| `utils/mobileLayout.spec.ts` | 配置读不读得出来、清单顺序、摆法回落、删格补格对账、外部页面那一格的键与开关 |
| `components/oa/mobile/useFormPlan.spec.ts` | 只出一节、系统取数不再并走、空值照样摆、四道闸、置顶上限、明细两档、入口开关、外部页面那张卡片与它的两道闸 |
| `components/oa/mobile/MobileFormSummary.spec.ts` | 屏幕上真是那样:不折叠、`—`、明细逐条、缩略图、卡片带对 `job`/`activity`/`slotKey`、开关没开时还是从前那版 |
| `components/oa/design/MobileLayoutPanel.spec.ts` | 清单对得上现在这张表、改动当场 emit、上不上屏写的是 `mobileHidden`(外部页面那一行例外,写配置的 `hidden`) |
| `views/oa/design/FormDesignerView.mobile.spec.ts` | 配完存得出去(`content.layout.mobile`)、重开读得回来、进撤销栈与未保存、删掉的格子不留死配置 |
后端那一头只验一件事:这份配置存出去还在。`clean_option_source(clean_formats(content))`
原样交回 `layout.mobile`(`api/design.py` 一行没动,跑一次内存里的函数就够,不建数据)。
## 6. 没做的
* **手机上没有第二、第三节**。要分节的话还是回到自动归置那版,用页签和分隔条说话;
这一档的存在理由就是"我就要一节"。
* **发起页与桌面不变**。这一档只管手机上那一屏只读的摆法,填单的那一屏仍是桌面那套网格。
* **不给"手机端必填""手机端可见范围"这类新语义**。那些是权限与校验,不是版式;
一旦在这一层掺进去,同一件事就有了两处判据。
* **手机上不内嵌外部页面**。那一整页在清单上是一格、在手机上是一张「打开」卡片——
卡片能配、能排序、能勾掉,iframe 不给。别人的系统在 390px 里嵌进来就是没法看,
桌面那一版也一样是给卡片。

View File

@ -25,7 +25,8 @@
| 这次补了什么 | §7 那张表十四处,七组:能配吗(**空转配置**:模板选「到达某环节」其实从不发;**只有审批环节能挂**:创建与归档配不了;**一个环节只能配一条**:两种时机凑不到一起)、配错了会不会静默失效(**存与读两种拼写**、**时刻与环节对不上**、**同一份报文发两次**)、界面承诺过头(**挡住处理人**)、条件管太宽(挂载的 `when` 顺手摁掉别人的模板)、**问错了时候**(配模板时就被追问环节时刻,于是模板自己绑死一条流程的环节 id)、**配好了又会烂**(那些校验只管保存那一次,环节 id 换了、模板删了没人回头看过 → §7.5 全库配置体检:接口 + 集成页横幅 + 一个当闸门的脚本)、**按钮配了不响**(界面上有「退回」「撤回」两颗钮,
报文里却没有这两个时刻——`go_back` / `reset_task` 压根不走 `_advance`,那两条动作一个字都不发 → §13) |
## 1. 先对齐这四种「什么时候发」
## 1. 先对齐这五种「什么时候发」
| 触发点 | 在哪配 | 数据是哪一刻的 | 典型用途 |
| --- | --- | --- | --- |
@ -33,9 +34,12 @@
| **到达**某环节 | L3 挂载 `trigger=arrive`(旧写法是 L2 模板 `trigger_event=activity`,只给存量配置留着) | 进入该环节那一刻(含上一环节刚改完的值) | 付款指令:流程一踏进付款环节就通知资金系统 |
| **本环节审批通过后** | L3 挂载 `trigger=leave` | 本环节审批人改过的值已落库、路由已选定、还没进下一环节 | 「部门经理批完就把状态和审批意见回写 ERP」 |
| **本环节被退回时** | L3 挂载 `trigger=goBack`(挂在**按「退回」的那一环**上,不是收单那一环);还能再按**退落到哪一环**(`goBackTo`)与**这一退是谁按的**(`goBackVia`,第三方调接口退的单独一档)各筛一道(§14) | 退回人这次的修改已落库、单子正要被打回去 | 「审批不通过就把状态与意见回写 ERP,让对面把那张待结算的单解挂」 |
| **本环节被撤回时** | L3 挂载 `trigger=recall`(挂在**被撤回那条已办所属的环节**上;发起环节这一刻 = 发起人撤回自己的提交) | 撤回那一刻(撤回**不改表单**) | 「对面刚按刚才那条草稿建了单,我这边撤回了,得通知它删掉」 |
**还有一种情况不在这四种里,也不该在这里找**:嵌进来的那一页,人**没保存就返回**了,要通知对面
| **本环节被撤回时** | L3 挂载 `trigger=recall`(挂在**被撤回那条已办所属的环节**上;发起环节这一刻 = 发起人撤回自己的提交) | 撤回那一刻(撤回**不改表单**) | 「对面刚按刚才那条草稿建了单,我这边撤回了,得通知它删掉」 |
| **这条流程被终止时** | **既不挂环节、也不在模板上**:`流程设计 → 流程信息 → 终止` 那一格(`oa_process.terminate_config.writeback`,时刻固定 `trigger=terminate`) | 终止那一刻的 `work.data`(归档前最后一次落库的值) | 「**只有这一条流程**被终止时要通知上游解挂」——写成模板上的终态勾选会被同表单的另一条流程跟着发,挂环节又挂不上(终止不是画布上的一环),§5.5 |
**还有一种情况不在这五种里,也不该在这里找**:嵌进来的那一页,人**没保存就返回**了,要通知对面
把按预留单号建起来的那张草稿删掉([embed-configuration-guide.md](embed-configuration-guide.md) §2.4)。
那一刻**还没有这张单**,而模板的报文、条件、幂等键、发件箱全都以单号为前提——所以它不是一条模板,
配在那条「可嵌入页面」上、发在那一趟嵌入会话上。界面把这件事写在两处:「什么时候发」那一格下面直接把
@ -83,6 +87,12 @@
| 结束 | **走到结束(归档)时**(就是 `arrive`) | 这一刻在 `_finish_work` **之前**:单据还没进终态,`{work.status}` 取到的是 `running`。只想要"定局之后"就改用「办结时」的模板(§5.5) |
| 作废 | **走到作废环节时**(就是 `arrive`) | 同上,只是这张单马上要变 `canceled`。要顺带冲销已发凭证,用配了「冲销模板」的终态模板(§5.5) |
五种时刻里只有「这条流程被终止时」**不属于任何环节**:它配在流程信息面板上,所以每一种环节的「写回挂载」
那一格里都看不见它,反过来说它也不需要点名环节(§5.5)。它仍复用环节挂载那套读法与形状
(`mapping.mount_plan` / `mount_blocks` / `mount_triggers`,时刻取值多一个 `TRIGGER_TERMINATE`),
条件、按模板分流的字段子集、失败策略、整批 `when` 与单格 `when` 全部照旧生效。
时刻与环节对不上时那条写回一条都不会发、而且不报错,所以:**界面上不给选**(那一格里只摆这一刻能勾的几个),
**保存流程时挡**、**全库体检也报**(手改 JSON、导入别处的流程、后来又把按钮关了,都可能配出这种死配置)。
判据只有一份:`mapping.TRIGGER_ACTIVITY_TYPES` / `TRIGGER_ACTIVITY_FLAGS`,前端 `formWriteback.ts` 镜像同一份(§13)。
@ -163,12 +173,14 @@
(`mapping.mount_of` / `mount_failure_policy` / `mount_fail_route`),设计期与运行期共用,
不再出现"界面存 `onFailure`、运行期读 `on_failure`、于是谁都没错但什么都没发生"。
## 3. 「什么时候发」只有两处能配,模板页那一格不算环节入口
## 3. 「什么时候发」只有三处能配,模板页那一格不算环节入口
| 这一刻在哪 | 在哪儿配 | 能配的东西 |
| --- | --- | --- |
| 这张单走进终态(办结 / 终止 / 作废) | 集成页的模板:「什么时候发」那一格 | 三条可以多勾,**也可以一条都不勾**(= 这条模板自己不自动发) |
| 流程走到某个环节的某一时刻 | 流程设计器选中环节 →「写回挂载」 | 时刻(到达 / 办完之后)、要发哪几个模板、整批条件、每一格的条件、要发的字段、失败策略 |
| 这张单走进终态(办结 / 终止 / 作废) | 集成页的模板:「什么时候发」那一格 | 三条可以多勾,**也可以一条都不勾**(= 这条模板自己不自动发)。**按绑定表单找齐**,同表单的每一条流程都会发 |
| 流程走到某个环节的某一时刻 | 流程设计器选中环节 →「写回挂载」 | 时刻(到达 / 办完之后 / 被退回 / 被撤回)、要发哪几个模板、整批条件、每一格的条件、要发的字段、失败策略 |
| 只有**这一条流程**被终止的那一刻 | 流程设计器 → 流程信息(meta 面板)→「终止」 | 终止那一刻发哪几个模板、整批条件与单格条件、要发的字段子集、失败策略(`oa_process.terminate_config.writeback`,§5.5) |
**环节那一刻不在模板页配**。以前那里也有一档「到达某环节」,要人在配模板的时候挑一条流程里的一个环节——
可那一刻他还没决定这张模板要挂在哪儿,只能挑一个最像的顶上;而环节 id 是每条流程自己的主键,
@ -296,8 +308,42 @@
三条终态**不挂环节**:在模板的「什么时候发」里勾办结 / 终止 / 作废(**三条可以多勾**,一条模板就能同时管办结与终止,
不用再复制两份映射),按绑定表单自动找齐(没绑表单的模板视为通用)。
面板底部那块「办结 / 终止 / 作废那一刻发什么」把这个表单上配了终态的模板列出来,哪个环节都没挂也能一眼看全。
### 5.5.1 「终止时」还有第二个入口:只给这一条流程配
三条终态的模板按**绑定表单**自动找齐,这带来的正是它的好处也是它的限制:同一张报销表单挂了两条流程
(比如「员工报销」与「领导报销」)时,"终止时要通知上游"这件事**没法只给其中一条流程配**——模板勾了终止,
两条流程终止时都会发。而终止又不是画布上的一环,挂不到任何一环上,L3 那一格帮不上忙。
所以流程自己留一格:`流程设计 → 流程信息(meta 面板)→ 终止`(存 `oa_process.terminate_config.writeback`),
只在这**一条流程**被终止时发。
| 比的是 | 模板自己勾终态(`trigger_events`) | 流程那一格(`terminate_config.writeback`) |
| --- | --- | --- |
| 生效范围 | 绑定这张表单的**所有**流程 | 就这一条流程 |
| 时刻取值 | 三条终态可以多勾(办结 / 终止 / 作废) | 固定 `terminate` 一个时刻 |
| 条件 / 字段子集 / 失败策略 | 模板上那道「哪些单才发」 | 挂载上的整批 `when` + 单格 `when` + 每模板字段子集 + `on_failure`,**与环节挂载同一套读法** |
| 报文上的辨认 | `event=terminated`、`event_key=''` | `event=terminated`、`event_key=terminate`、`phase=terminate` |
| 谁先入队 | `outbox.enqueue_event` | `outbox.enqueue_terminate`,同一事务、紧接着,仍都在 `db.delete(work)` **之前**(报文要用还没搬走的 `work.data` 渲染) |
| 冲销 | 那一刻同样走 `handle_reversal` | 冲销与这一格无关:它只管发,冲销照旧按**原模板**上填的「冲销模板」处理 |
**同一个模板两处都配就各发一条**,不会互相吃掉:幂等键里 `event_key` 那一段不一样(`terminate` 对空),
天然两个键。这不是 bug 也不是重复发送,但九成是配的人没意识到自己配了两遍,所以**设计器选模板时就地点名**
(那一格下面直接写出「这个模板还勾了终止,那一刻会各发一条」)。终止那一刻 `{activity.id}` 取到空串
(没有环节),`{action.phase_name}` 是「流程终止时」,`{action.opinion}` 是终止原因(界面接口上已改成必填)。
这一格是**第三处绑定点**,三处可见性一处都不许漏(漏一处就等于界面在那儿撒谎):
- **模板页底部那份「什么时候真的会发」**(`GET /design/integrations/{code}/firing`)如今合并四处:
模板勾的终态 + 旧写法点名的环节 + 环节挂载 + 这一格终止挂载(`terminateMounts`)。只合前两处时,
一条只被这一格点名、自己什么终态都没勾的模板,在这屏显示"还没有触发点,一条都不会自动发",
而它其实每被终止一次就发一次;
- **保存流程**就报三种病,判据与运行期逐条对得上(`mapping.mount_code_problems`):模板被删了、
被停用了、绑的是另一张表单——那一条模板那一刻都发不出去,别存进去当没看见;
- **全库体检**(`GET /design/integrations/audit`)也扫这一格,单独归一类「终止挂载」并给流程设计器的
入口:模板是**保存之后**才被删、被停用的,保存那道闸这辈子都碰不到这种病(§7.5 同一条理由)。
**作废要分三件事**,配法不一样:
| 想要什么 | 怎么配 | 落库会看到什么 |
@ -431,15 +477,28 @@
八种病各造一次,每一种都被点名;同一模板勾两个时刻(`leave` + `goBack`)这一条新用法不被误判成重复,
而 `arrive` + `leave` 同模板仍旧点名;干净的那条模板不冤枉;每条结论都带着能跳转的目标;
挂载那一层的病落在流程上(不是模板上);脏成 `{}` 的 `trigger_events` 被启动自检洗回数组;
- **流程那一格终止挂载**(§5.5.1,`scripts/check_terminate_control.py` D 组)→ 终止那一刻入队一条,
报文认得出是终止发的(`event=terminated` / `event_key=terminate` / `phase=terminate` 且渲染得出单号);
办结那一刻一条都不误发;挂载上的条件不成立时不入队、不留死信;模板绑的是另一张表单不发;
**模板被停用也不发**(界面那句「已停用,终止那一刻不会发出去」必须是真的);
同一模板既挂这一格又勾了终态 → 两条报文、两个幂等键,不静默吃掉一条;配了冲销模板时终止自动反向冲一条;
- **这一格的三种可见性**(同上 F 组)→ 保存流程点名三种病(模板被删 / 被停用 / 绑错表单),没病的那条不冤枉,
还没定表单时不判绑错表单那条;`GET /design/integrations/audit` 扫到它并单独归「终止挂载」一类;
`GET /design/integrations/{code}/firing` 的 `terminateMounts` 带上它,没被任何一格点名的模板那一栏是空的
(`IntegrationView.trigger.spec.ts` / `IntegrationView.audit.spec.ts` 各钉一条);
- 集成页那条横幅(`IntegrationView.audit.spec.ts`)→ 有病才出现、条数与逐条点名都对、
模板那一类点一下跳进编辑器、挂载那一类给流程设计器入口、体检读不到时不弹错也不拖倒列表;
- 前端 `npx vue-tsc --noEmit` 干净、`vitest` 77 份 895 项全绿(含 `IntegrationView.trigger.spec.ts`、
模板那一类点一下跳进编辑器、挂载与终止挂载那一类给流程设计器入口、体检读不到时不弹错也不拖倒列表;
- 前端 `npx vue-tsc --noEmit` 干净、`vitest` 113 份 1259 项全绿(含 `IntegrationView.trigger.spec.ts`、
`IntegrationView.audit.spec.ts` 与新加的 `formWriteback.moments.spec.ts`(14 条)/
`WritebackPanel.moments.spec.ts`(7 条))、
`WritebackPanel.moments.spec.ts`(7 条),以及终止那一组的 `terminateConfig.ts`(18 条)/
`approvalRecord.terminate`(8 条)/ `ApprovalRecord.terminate`(5 条)/
`ProcessDesignerView.terminate`(8 条)/ `WorkDetailView.terminate`(9 条)/
`CreatedListView.terminate`(3 条))、
后端 `scripts/check_writeback_trigger.py`(30 项)、`scripts/check_writeback_revisit.py`(36 条)、
`scripts/check_outbox_wake.py`(13 条:入队提交当场叫醒、回滚与无变化的并回不空叫、值变了要刷新也叫醒、一轮发干净一张单)、
`scripts/check_writeback_action.py`(42 条,§13)、`scripts/check_writeback_config.py`(17 项)、
`scripts/check_seed_repairs.py`(23 项)、`scripts/check_schema_bootstrap.py`(20 项)、
`scripts/check_terminate_control.py`(55 项,全程内存 sqlite,一条语句都不碰生产库)、
`check_schema_snapshot.py`、`check_schema_bootstrap.py`、`check_globals.py` 全绿;`eslint` 这一层本次改到的文件干净,
只剩 `NodeInspector.vue` 那十条 `vue/no-mutating-props`——它们是仓库既有欠账(HEAD 版本同样十条),不在这次范围里。

View File

@ -79,6 +79,24 @@
之所以要专门知会:表单字段会驱动后面的条件必批与分支判断,「中途被人改过又不留痕」等于
流转方向被悄悄换了还没人负责。管理员改的更要写清楚——被改的人往往最后才知道。
## 4.1 改完表单,标题与三张列表一起对齐
表单里那一格「流程标题」(``type: title``)就是 ``work.title`` 的出处,所以管理员改掉那一格、
或者改掉标题规则引用的那几格,**都算改标题**。引擎走的是与审批人办单同一句 ``titles.refresh``,
重算出来之后连同**在途的待办与待阅**一起改名(``engine._refresh_title``)。少了这一步就是用户
报的那个现象:面板里明明改好了、上面那张卡片的标题也换了,列表上那一行还写着老那一句——
待办列表、待阅列表、监控列表读的都是各行自己那一份 ``title``(为的是列表不必回查单据)。
两条分寸一起钉着:
- **反向的闸**:规则没开「表单变了重算标题」(``refresh=false``)时,改普通字段**不该**替这张单
重取名字,只有直接改标题那一格才换。对齐不等于每次修正都顺手改名单。
- **已办 / 已阅不动**:那是历史快照,那个人当时批的就是那一句,事后替他改名字反而对不上内容。
保存之前面板上还先预告一句「保存后标题会变成 …」(``POST /job/{job}/title/preview``,只读不写库,
可见范围与 ``/admin/work/{job}/data`` 同一道数据范围筛)——改标题这件事看不见摸不着,说出来比让人
改完再去列表里核对一趟便宜。判据在 ``backend/scripts/check_intervention_title.py``。
## 5. 权限与数据范围:一码到底,没加新权限点
六个干预接口全部挂既有的 ``monitor:work``,数据范围与「终止」共用同一道筛
@ -169,6 +187,9 @@ POST /admin/work/{job}/transfer 整单改派 {identities, opinion}
办结 / 终止之后 ``oa_work`` 那行会被搬进归档表,所以 ``_running_work`` 先回查一眼
``WorkCompleted``,好把「这单早走完了」和「查无此单」分成两句话说。
6. 整单催办:并行压着几条就催几条、每条 ``press_count`` 各 +1、每人收到一条催办提醒。
7. 改数据改到标题那一格:单据、在途待办、待阅三处一起改名,监控列表按新标题搜得到这张单;
规则开了自动重算时,改它引用的字段照样重算一句并写回那一格;``refresh=false`` 时改普通字段
不许替这张单重取名字。这一条有常驻判据:``PYTHONPATH=. python3 scripts/check_intervention_title.py``。
外加仓库里那三条守卫:``check_globals.py``、``check_route_guards.py``、
``check_schema_snapshot.py``(改了 ``models.py`` 记得先 ``dump_schema.py`` 再回归),

View File

@ -0,0 +1,29 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>预览:一台 390 的屏</title>
<style>
body {
margin: 0;
background: #e9eaee;
}
iframe {
display: block;
border: 0;
width: var(--w, 390px);
height: var(--h, 844px);
}
</style>
</head>
<body>
<iframe id="f"></iframe>
<script>
const p = new URLSearchParams(location.search);
// 套一层 iframe 是因为 headless Chrome 把窗口宽度钳在 500,量不到真手机的 390
document.documentElement.style.setProperty('--w', (p.get('w') || 390) + 'px');
document.documentElement.style.setProperty('--h', (p.get('h') || 844) + 'px');
document.getElementById('f').src = p.get('src') || '/preview-mobile.html';
</script>
</body>
</html>

View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>手机版式预览</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/dev/mobilePreview.ts"></script>
</body>
</html>

View File

@ -14,6 +14,7 @@ import type {
ProcessSimulation,
ProcessDef,
ProcessSerialTiming,
ProcessTerminateConfig,
ProcessTitle,
RouteDef,
StartersPreview,
@ -128,6 +129,8 @@ export interface DesignPayload {
title_config?: ProcessTitle
/** 编号生成时机;不传当没改,见 utils/serialTiming.ts */
serial_config?: ProcessSerialTiming
/** 发起人终止的规矩;不传当没改,见 utils/terminateConfig.ts */
terminate_config?: ProcessTerminateConfig
}
export function saveDesign(id: string, payload: DesignPayload): Promise<ProcessDef> {

View File

@ -17,8 +17,10 @@
<button
@click="handleConfirm"
type="button"
:disabled="confirmDisabled"
:class="[
'rounded-md px-4 py-2 text-sm font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-dark-800',
confirmDisabled && 'cursor-not-allowed opacity-50 hover:!bg-red-600',
danger
? 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
: 'bg-primary-600 hover:bg-primary-700 focus:ring-primary-500'
@ -45,6 +47,8 @@ interface Props {
confirmText?: string
cancelText?: string
danger?: boolean
/** 必填项还没填齐时按不住:让「说清楚为什么」这一步在弹窗里就挡住,而不是提交后被后端退回 */
confirmDisabled?: boolean
}
interface Emits {
@ -52,8 +56,10 @@ interface Emits {
(e: 'cancel'): void
}
const props = withDefaults(defineProps<Props>(), {
danger: false
danger: false,
confirmDisabled: false
})
const confirmText = computed(() => props.confirmText || t('common.confirm'))

View File

@ -1,23 +1,27 @@
<template>
<Teleport to="body">
<!-- 桌面上贴右上、宽 320 起(照旧);手机上换成贴底居中一条:拇指够得着,
也不会盖住详情页那张吸底操作栏(bottom-20 抬过了底部标签栏那 3.5rem)。
窄屏是默认档,md: 起才把 left 放开、改回贴右上——不然桌面那几条会跑到左边。 -->
<div
class="pointer-events-none fixed right-4 top-4 z-[9999] space-y-3"
class="pointer-events-none fixed inset-x-3 bottom-20 z-[9999] space-y-2 md:inset-x-auto md:bottom-auto md:right-4 md:top-4 md:space-y-3"
aria-live="polite"
aria-atomic="true"
>
<TransitionGroup
enter-active-class="transition ease-out duration-300"
enter-from-class="opacity-0 translate-x-full"
enter-to-class="opacity-100 translate-x-0"
enter-from-class="opacity-0 translate-y-4 md:translate-x-full md:translate-y-0"
enter-to-class="opacity-100 translate-y-0"
leave-active-class="transition ease-in duration-200"
leave-from-class="opacity-100 translate-x-0"
leave-to-class="opacity-0 translate-x-full"
leave-from-class="opacity-100 translate-y-0"
leave-to-class="opacity-0 translate-y-4 md:translate-x-full"
>
<div
v-for="toast in toasts"
:key="toast.id"
:class="[
'pointer-events-auto min-w-[320px] max-w-md overflow-hidden rounded-lg shadow-lg',
'pointer-events-auto overflow-hidden rounded-lg shadow-lg',
'w-full min-w-0 max-w-none md:min-w-[320px] md:max-w-md',
'bg-white dark:bg-dark-800',
'border-l-4',
getBorderColor(toast.type)
@ -52,10 +56,10 @@
</p>
</div>
<!-- Close button -->
<!-- Close button:手机上这条自己会走,不必再留一颗让人去点的叉 -->
<button
@click="removeToast(toast.id)"
class="-m-1 flex-shrink-0 rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-dark-700 dark:hover:text-gray-300"
class="-m-1 hidden flex-shrink-0 rounded p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-dark-700 dark:hover:text-gray-300 md:block"
aria-label="Close notification"
>
<Icon name="x" size="sm" />

View File

@ -45,6 +45,7 @@ export const ICONS = {
table: 'M4 5h16a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6a1 1 0 011-1zM3 10h18M9 5v14M15 5v14',
// 标签页:一块面板顶上挂着两枚页签
window: 'M3.75 4.5h16.5c.621 0 1.125.504 1.125 1.125v12.75c0 .621-.504 1.125-1.125 1.125H3.75c-.621 0-1.125-.504-1.125-1.125V5.625c0-.621.504-1.125 1.125-1.125zM3 9h18M7.125 6.75h3.75m2.25 0h3.75',
phone: 'M10.5 1.5H8.25A2.25 2.25 0 006 3.75v16.5a2.25 2.25 0 002.25 2.25h7.5A2.25 2.25 0 0018 20.25V3.75a2.25 2.25 0 00-2.25-2.25H13.5m-3 0V3h3V1.5m-3 0h3m-3 18.75h3',
mousePointer: 'M5 3l6.5 17 2.2-6.3L20 11.5 5 3z',
tag: 'M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.782.872 2.655.495a18.72 18.72 0 003.387-1.634 3 3 0 001.273-3.326l-.448-1.791a18.72 18.72 0 01-1.634-3.387 3 3 0 00-.495-2.655L9.568 3zM6 6h.008v.008H6V6z',
expand: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5',

View File

@ -3,9 +3,25 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { computed } from 'vue'
import { createI18n } from 'vue-i18n'
import zh from '@/i18n/locales/zh'
import AppHeader from './AppHeader.vue'
import AppLayout from './AppLayout.vue'
import AppSidebar from './AppSidebar.vue'
/** 版式闸门:用例要说摆就摆「这台手机走的是手机版面」,不必去伪造 matchMedia。 */
const shell = vi.hoisted(() => ({ phoneShell: false }))
vi.mock('@/composables/useMobileShell', () => ({
useChromeless: () => ({ chromeless: computed(() => false) }),
useMobileShell: () => ({
isPhone: computed(() => shell.phoneShell),
desktopPinned: computed(() => false),
phoneShell: computed(() => shell.phoneShell),
pinDesktop: vi.fn(),
fontScale: computed(() => 'm'),
setFontScale: vi.fn()
})
}))
vi.mock('@/api', () => ({
supportAPI: {
@ -23,7 +39,8 @@ const Page = { template: '<div data-test="page">正文</div>' }
* (见 style.css 里的 --app-shell-max),画布类路由在 meta 上标 fullWidth 才铺满。
* 这条判据一旦丢掉,宽屏上表格与输入框又会拉回两千多像素。
*/
async function open(path: string) {
async function open(path: string, phone = false) {
shell.phoneShell = phone
const pinia = createPinia()
setActivePinia(pinia)
const router = createRouter({
@ -66,3 +83,27 @@ describe('AppLayout:宽屏正文收口', () => {
expect(wrapper.find('main > div [data-test="page"]').exists()).toBe(true)
})
})
describe('AppLayout:手机版式让开那一条顶栏', () => {
it('手机上整条顶栏都不挂(站点名、通知、语言、深色、头像都在别处了)', async () => {
const wrapper = await open('/todo', true)
expect(wrapper.findComponent(AppHeader).exists()).toBe(false)
})
it('底部三格常驻那几页不挂细栏,别的页面挂那一行 44px', async () => {
const root = await open('/todo', true)
expect(root.find('[data-test="m-topbar"]').exists()).toBe(false)
const child = await open('/design/processes/p1', true)
expect(child.find('[data-test="m-topbar"]').exists()).toBe(true)
expect(child.find('[data-test="m-topbar"]').text()).toContain('流程设计')
})
it('手机上左侧那个抽屉整块不挂,桌面与平板那一档照旧', async () => {
const wrapper = await open('/todo', true)
expect(wrapper.findComponent(AppSidebar).exists()).toBe(false)
const tablet = await open('/todo')
expect(tablet.findComponent(AppSidebar).exists()).toBe(true)
})
it('桌面上照旧挂顶栏,也不挂那条细栏', async () => {
const wrapper = await open('/design/processes/p1')
expect(wrapper.findComponent(AppHeader).exists()).toBe(true)
expect(wrapper.find('[data-test="m-topbar"]').exists()).toBe(false)
})
})

View File

@ -2,13 +2,32 @@
<div class="min-h-screen bg-gray-50 dark:bg-dark-950">
<div class="pointer-events-none fixed inset-0 bg-mesh-gradient"></div>
<AppSidebar />
<!-- 手机上那侧抽屉整块不挂:抽屉的拉手本来就在顶栏那颗汉堡上,顶栏都让掉了,
留着它只是一堆进不去的 DOM。入口改走「我的」那一屏(views/oa/ProfileView.vue 手机档)。
768~1023 那一档照旧:汉堡在,抽屉也在。 -->
<AppSidebar v-if="!phoneShell" />
<div
class="relative min-h-screen transition-all duration-300"
:class="[sidebarCollapsed ? 'lg:ml-[72px]' : 'lg:ml-64']"
>
<AppHeader />
<!-- 窄屏整条顶栏都不摆(截图里那一条:站点名、通知、语言、深色、头像)。
手机上这几件事各有各的去处:页名与返回在下面那条 44px 的细栏上,
通知、外观、字号、退出全收进「我的」。详情页连细栏也不要,见下一句 chromeless。 -->
<AppHeader v-if="!chromeless && !phoneShell" />
<MobileTopBar v-if="phoneShell && !chromeless && !isTabRoot" />
<!-- 有新版本:桌面上是顶栏那颗钮,手机上顶栏没了,就换成一横条,一行说完 -->
<div
v-if="phoneShell && updateReady"
class="sticky top-11 z-20 flex items-center gap-2 bg-primary-50 px-4 py-2 text-[13px] text-primary-800 dark:bg-primary-900/30 dark:text-primary-100"
data-test="m-update"
>
<Icon name="sync" class="h-4 w-4 flex-shrink-0" />
<span class="min-w-0 flex-1">{{ t('pwa.updateReady') }}</span>
<button type="button" class="flex-shrink-0 font-medium underline" @click="applyUpdate">
{{ t('pwa.refresh') }}
</button>
</div>
<!-- 断网了就先说清楚:页面照常画着,但上面是上次那份数,别让审批人当真 -->
<div
@ -19,7 +38,9 @@
<span>{{ t('mobile.offline') }}</span>
</div>
<main class="p-4 md:p-6 lg:p-8" :style="{ paddingBottom: bottomInset }">
<!-- chromeless 那一档整块屏都交给页面自己:内边距也一并让掉,
否则手机版式那几块通铺的面板左右各被切出 16px 的缝,吸顶栏后面会漏字。 -->
<main :class="chromeless ? 'p-0' : 'p-4 md:p-6 lg:p-8'" :style="{ paddingBottom: bottomInset }">
<!-- 宽屏上把正文收在 .app-shell 这条居中的宽度里;设计器这类画布页要的是
每一像素的横向空间,路由上标了 fullWidth 就照旧铺满。 -->
<div :class="fullWidth ? '' : 'app-shell'">
@ -32,7 +53,7 @@
<!-- Mobile drawer backdrop -->
<div
v-if="mobileOpen"
v-if="!phoneShell && mobileOpen"
class="fixed inset-0 z-30 bg-black/40 lg:hidden"
@click="appStore.setMobileOpen(false)"
></div>
@ -46,10 +67,13 @@ import { useOnline } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import { useAppStore } from '@/stores/app'
import { useChromeless, useMobileShell } from '@/composables/useMobileShell'
import { useMobileNav } from '@/composables/useMobileNav'
import { usePwa } from '@/composables/usePwa'
import AppSidebar from './AppSidebar.vue'
import AppHeader from './AppHeader.vue'
import MobileTabBar from './MobileTabBar.vue'
import MobileTopBar from './MobileTopBar.vue'
/**
* 桌面靠左侧边栏,窄屏靠底部标签栏,两条导航在同一套权限判据下说法一致。
@ -62,7 +86,15 @@ const { t } = useI18n()
const route = useRoute()
const appStore = useAppStore()
const online = useOnline()
const { isNarrow, bottomInset } = useMobileNav()
const { isNarrow, bottomInset: navBottomInset } = useMobileNav()
const { chromeless } = useChromeless()
const { phoneShell } = useMobileShell()
const { updateReady, applyUpdate } = usePwa()
/** 底部三格常驻的那几页不挂那条细栏:它们本来就在导航上,再加一行标题只把正文往下推。 */
const TAB_ROOTS = ['/workbench', '/todo', '/profile']
const isTabRoot = computed(() => TAB_ROOTS.some((one) => route.path === one || route.path.startsWith(`${one}/`)))
/** 标签栏在场时底下才要让那一段;手机版式下的详情页自己管那条吸底栏 */
const bottomInset = computed(() => (chromeless.value ? '0px' : navBottomInset.value))
const sidebarCollapsed = computed(() => appStore.sidebarCollapsed)
const mobileOpen = computed(() => appStore.mobileOpen)

View File

@ -0,0 +1,103 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import { useAppStore } from '@/stores/app'
import { useAuthStore } from '@/stores/auth'
import type { User } from '@/types'
import MobileTabBar from './MobileTabBar.vue'
/** 版式闸门在这一档里是只读判据,用例要把「这台手机钉过电脑版」这件事摆出来才好办。 */
const shell = vi.hoisted(() => ({ isPhone: false, desktopPinned: false, pinDesktop: vi.fn() }))
vi.mock('@/composables/useMobileShell', () => ({
useChromeless: () => ({ chromeless: false }),
useMobileShell: () => ({ isPhone: shell.isPhone, desktopPinned: shell.desktopPinned, pinDesktop: shell.pinDesktop })
}))
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
// 每用例从「没钉过电脑版」起步,免得上一例留下的状态串到下一例
shell.isPhone = false
shell.desktopPinned = false
})
const ALL = ['work:workbench', 'work:todo', 'work:read', 'work:start', 'work:profile']
async function render(path = '/workbench', permissions: string[] = ALL) {
const pinia = createPinia()
setActivePinia(pinia)
useAuthStore().$patch({
user: {
id: 'u1',
account: 'boss',
display_name: '周总',
permissions
} as unknown as User,
token: 'token'
} as never)
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/workbench', component: { template: '<div />' } },
{ path: '/todo', component: { template: '<div />' } },
{ path: '/start', component: { template: '<div />' } },
{ path: '/profile', component: { template: '<div />' } }
]
})
await router.push(path)
await router.isReady()
return mount(MobileTabBar, { global: { plugins: [router, pinia, i18n] } })
}
const items = (wrapper: Awaited<ReturnType<typeof render>>) =>
wrapper.findAll('nav a').map((link) => ({
href: link.attributes('href'),
text: link.text().replace(/\s+/g, '')
}))
describe('手机底部那一条', () => {
it('只有首页、待办、我的:发起流程不再常驻', async () => {
expect(await items(await render())).toEqual([
{ href: '/workbench', text: '首页' },
{ href: '/todo', text: '待办' },
{ href: '/profile', text: '我的' }
])
})
it('待办那一格带着角标计数', async () => {
const wrapper = await render('/todo')
useAppStore().todoCount = 12
await flushPromises()
// 角标挂在图标那一块的右上角,读屏顺序里它在名字前面
expect(items(wrapper)[1]).toEqual({ href: '/todo', text: '12待办' })
})
it('没那条权限的人那一格就不摆', async () => {
expect((await items(await render('/workbench', ['work:workbench', 'work:todo']))).map((item) => item.href)).toEqual(
['/workbench', '/todo']
)
})
it('钉在电脑版时,标签栏头顶留一颗「看手机版」', async () => {
shell.isPhone = true
shell.desktopPinned = true
const wrapper = await render()
const back = wrapper.find('[data-test="m-to-phone"]')
expect(back.text().replace(/\s+/g, '')).toBe('看手机版')
await back.trigger('click')
expect(shell.pinDesktop).toHaveBeenCalledWith(false)
})
it('没钉在电脑版就不摆这颗钮:正常手机上它只会碍事', async () => {
shell.isPhone = true
shell.desktopPinned = false
expect((await render()).find('[data-test="m-to-phone"]').exists()).toBe(false)
shell.isPhone = false
shell.desktopPinned = true
expect((await render()).find('[data-test="m-to-phone"]').exists()).toBe(false)
})
})

View File

@ -1,6 +1,19 @@
<template>
<!-- 这台手机之前点过「看电脑版」:那一档把整个手机版式都关掉了,而这一条只看屏幕宽度、
照旧贴着下沿,那就顺手在它头顶留一个回去的口子。少了这颗钮,手机上点错一次就再也切不回来,
只能去清缓存。 -->
<button
v-if="isPhone && desktopPinned"
type="button"
class="fixed bottom-16 right-3 z-30 flex items-center gap-1 rounded-full border border-gray-200 bg-white/95 px-3 py-1.5 text-xs text-gray-600 shadow-lg backdrop-blur active:scale-95 dark:border-dark-700 dark:bg-dark-800/95 dark:text-dark-300"
data-test="m-to-phone"
@click="pinDesktop(false)"
>
<Icon name="phone" class="h-3.5 w-3.5" />
{{ t('mobile.toPhone') }}
</button>
<nav
v-if="items.length"
v-if="items.length && !chromeless"
class="fixed inset-x-0 bottom-0 z-30 flex border-t lg:hidden border-gray-200 bg-white/95 pb-[env(safe-area-inset-bottom)] backdrop-blur dark:border-dark-700 dark:bg-dark-900/95"
:aria-label="t('mobile.nav')"
>
@ -34,13 +47,15 @@ import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import { useChromeless, useMobileShell } from '@/composables/useMobileShell'
import { useAppStore } from '@/stores/app'
import { useAuthStore } from '@/stores/auth'
/**
* 手机上没有侧边栏可用(它是抽屉,藏在一层遮罩后面),最常用的四件事得一直伸手就到。
* 手机上没有侧边栏可用(它是抽屉,藏在一层遮罩后面),最常用的三件事得一直伸手就到。
*
* 这一条固定贴在屏幕下沿,权限判据与侧边栏同一套(`authStore.can`),所以「看不看得到」
* 只有三格:手机上「发起流程」是偶尔一次的事,常驻一格反而把常用的挤小了,它搬到首页
* (components/oa/mobile/MobileHome.vue 底部那颗钮)。这一条固定贴在屏幕下沿,权限判据与侧边栏同一套(`authStore.can`),所以「看不看得到」
* 在两处不会说法不一。待办角标读的是 appStore 里那份计数——由 AppLayout 统一去取,
* 免得侧边栏和这里各打一次同一个接口、还各说一个数。
*/
@ -60,13 +75,31 @@ const route = useRoute()
const appStore = useAppStore()
const authStore = useAuthStore()
const { chromeless } = useChromeless()
const { isPhone, desktopPinned, pinDesktop } = useMobileShell()
const items = computed<TabItem[]>(() =>
(
[
{ path: '/workbench', label: t('mobile.workbench'), permission: 'work:workbench', icon: 'grid', exact: true },
{ path: '/todo', label: t('mobile.todo'), permission: 'work:todo', icon: 'inbox', badge: appStore.todoCount },
{ path: '/start', label: t('mobile.start'), permission: 'work:start', icon: 'plus' },
{ path: '/profile', label: t('mobile.mine'), permission: 'work:profile', icon: 'user' }
{
path: '/workbench',
label: t('mobile.home'),
permission: 'work:workbench',
icon: 'home',
exact: true
},
{
path: '/todo',
label: t('mobile.todo'),
permission: 'work:todo',
icon: 'inbox',
badge: appStore.todoCount
},
{
path: '/profile',
label: t('mobile.mine'),
permission: 'work:profile',
icon: 'user'
}
] as TabItem[]
).filter((item) => authStore.can(item.permission))
)

View File

@ -0,0 +1,58 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import { useAppStore } from '@/stores/app'
import MobileTopBar from './MobileTopBar.vue'
/**
* 手机上那条 44px 细栏只管两件事:页名与返回。
* 它挂在哪几页由 AppLayout 判(见 AppLayout.spec),这里只测它自己摆的东西。
*/
async function render(path: string, meta: Record<string, unknown> = {}) {
const pinia = createPinia()
setActivePinia(pinia)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path, name: 'page', component: { template: '<div />' }, meta }]
})
await router.push(path)
await router.isReady()
const back = vi.spyOn(router, 'back')
const replace = vi.spyOn(router, 'replace')
const wrapper = mount(MobileTopBar, { global: { plugins: [router, pinia, i18n] } })
await flushPromises()
return { wrapper, back, replace }
}
describe('MobileTopBar:返回与页名', () => {
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
it('页名取路由自己标的 titleKey,别处不再挂站点名', async () => {
const { wrapper } = await render('/done', { titleKey: 'nav.myDone' })
expect(wrapper.find('[data-test="m-topbar"]').text()).toBe('我的已办')
expect(wrapper.find('[data-test="m-topbar"]').text()).not.toContain('UnisOA')
})
it('没标页名就用站点名,不留一条空栏', async () => {
const { wrapper } = await render('/somewhere')
useAppStore().siteName = '某一套站点名'
await flushPromises()
expect(wrapper.find('[data-test="m-topbar"]').text()).toContain('某一套站点名')
})
it('返回那颗只写返回这一件事', async () => {
const { wrapper, back, replace } = await render('/done', { titleKey: 'nav.myDone' })
const btn = wrapper.find('[data-test="m-top-back"]')
expect(btn.attributes('aria-label')).toBe('返回')
await btn.trigger('click')
// 浏览器里后退得动;直达进来没有来路时退回第一屏,两条都算把安全带好了
expect(back.mock.calls.length + replace.mock.calls.length).toBe(1)
})
})

View File

@ -0,0 +1,52 @@
<template>
<!-- 手机上替代顶栏的那一条:只有返回与页名。
桌面上那一条挂着站点名、通知、语言、深色、头像——在 390px 上它比正文还高,
而这些东西在手机上各有各的去处(通知与外观在「我的」,页名就在这条上)。 -->
<div
class="sticky top-0 z-20 flex h-11 items-center gap-1 border-b border-gray-100 bg-white/95 px-1.5 backdrop-blur dark:border-dark-700 dark:bg-dark-800/95"
data-test="m-topbar"
>
<button
type="button"
class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
:aria-label="t('common.back')"
data-test="m-top-back"
@click="back"
>
<Icon name="arrowLeft" class="h-5 w-5 text-gray-700 dark:text-dark-200" />
</button>
<p class="min-w-0 flex-1 truncate text-[15px] font-semibold text-gray-900 dark:text-white">{{ title }}</p>
<span class="w-9 flex-shrink-0"></span>
</div>
</template>
<script setup lang="ts">
/**
* 手机上子页面的顶栏:返回 + 页名,一行 44px,别的都不摆。
*
* 底部那三格标签常驻的页面(首页 / 待办 / 我的)不挂这一条——它们本来就在导航上,
* 再加一行标题只是把正文往下推。从首页卡片点进去的那些页面(已办、待阅、我发起的、
* 草稿、发起流程、委托、说明……)才需要它:那儿没有别的返回方式了。
*/
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import { useAppStore } from '@/stores/app'
import { landingPath } from '@/utils/returnPath'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const title = computed(() => {
const key = route.meta?.titleKey as string | undefined
return key ? t(key) : appStore.siteName
})
function back() {
if (window.history.length > 1) router.back()
else router.replace(landingPath())
}
</script>

View File

@ -0,0 +1,114 @@
// @vitest-environment jsdom
/**
* 审批记录里那一句「由某某终止」。
*
* 判据层已经由 utils/approvalRecord.terminate.spec.ts 钉过,这里钉的是**人看得见的
* 那一行**:那一行仍然挂在持有人名下(他的已办要看得见这张单),但必须另说一句是
* 谁按的——否则「部门主管给我终止了」这句误读没有任何地方能纠正它。
* 顺带钉终止那条留痕:它排在「全部事件」里,且不拿「部门主管 → 部门主管」冒充一次流转。
*/
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createI18n } from 'vue-i18n'
import zh from '@/i18n/locales/zh'
import ApprovalRecord from './ApprovalRecord.vue'
import type { TaskCompletedItem, WorkLogItem } from '@/types'
function terminatedRow(over: Partial<TaskCompletedItem> = {}): TaskCompletedItem {
return {
id: 'row-terminate',
activity_name: '部门主管',
identity: 'chenshenggang',
identity_name: '陈晟罡',
unit_name: '副总经理',
route_name: '终止',
opinion: '金额填错了,重发一张',
completed_time: '2026-11-04 10:03:33',
start_time: '2026-11-03 17:01:14',
duration: 61338,
processing_type: 'terminate',
operator: 'zhangjinjie',
operator_name: '张锦杰',
attachments: [],
...over
} as TaskCompletedItem
}
function terminateLog(): WorkLogItem {
return {
id: 'log-terminate',
type: 'terminate',
from_activity_name: '部门主管',
from_activity_type: 'manual',
from_identity_name: '张锦杰',
from_opinion: '张锦杰 终止了流程:金额填错了,重发一张',
arrived_activity_name: '部门主管',
arrived_activity_type: 'manual',
arrived_time: '2026-11-04 10:03:33',
route_name: '',
duration: 0
} as WorkLogItem
}
function mountRecord(props: Record<string, unknown>) {
const i18n = createI18n({ legacy: false, locale: 'zh', messages: { zh }, missingWarn: false, fallbackWarn: false })
setActivePinia(createPinia())
return mount(ApprovalRecord, {
props: { items: [], routes: [], pending: [], start: null, comments: [], logs: [], ...props } as never,
global: {
plugins: [i18n],
stubs: { AttachmentGallery: true, ConfirmDialog: true, OpinionComposer: true, PeoplePicker: true }
}
})
}
describe('终止在审批记录里说的那两句话', () => {
it('A1 那一行还在持有人名下,同时另说一句是谁按的', () => {
const wrapper = mountRecord({ items: [terminatedRow()] })
const text = wrapper.text()
expect(text).toContain('部门主管')
expect(text).toContain('陈晟罡')
expect(text).toContain('终止')
expect(text).toContain('由 张锦杰 终止')
// 原因是必填那句,别再是「流程终止」四个字
expect(text).toContain('金额填错了,重发一张')
})
it('A2 自己终止掉自己手上那条待办时不啰嗦这一句', () => {
const wrapper = mountRecord({
items: [terminatedRow({ identity: 'zhangjinjie', identity_name: '张锦杰', operator: 'zhangjinjie', operator_name: '张锦杰' })]
})
expect(wrapper.text()).not.toContain('由 张锦杰 终止')
})
it('A3 本人自己批完的那一步本来就没有这一句', () => {
const wrapper = mountRecord({
items: [terminatedRow({ processing_type: 'normal', operator: '', operator_name: '', opinion: '' })]
})
expect(wrapper.text()).not.toContain('由 张锦杰 终止')
})
/** 引擎事件默认收着,要点开顶上那颗「全部事件」。 */
function showEvents(wrapper: ReturnType<typeof mountRecord>) {
const button = wrapper.findAll('button').find((node) => node.text().includes('全部事件'))
expect(button, '没有全部事件那颗钮').toBeTruthy()
button!.trigger('click')
return wrapper.vm.$nextTick()
}
it('B1 终止那条留痕排在「全部事件」里,且不报「部门主管 → 部门主管」', async () => {
const wrapper = mountRecord({ items: [terminatedRow()], logs: [terminateLog()] })
await showEvents(wrapper)
const text = wrapper.text()
expect(text).toContain('张锦杰 终止了流程:金额填错了,重发一张')
expect(text).not.toContain('部门主管 → 部门主管')
})
it('B2 不开「全部事件」时不排它,审批序号也不被它占掉', () => {
const plain = mountRecord({ items: [terminatedRow()], logs: [terminateLog()] })
expect(plain.text()).not.toContain('张锦杰 终止了流程')
expect(plain.text()).toContain('共 1 步')
})
})

View File

@ -94,10 +94,21 @@
<span class="text-xs text-gray-400">{{ time(entry) }}</span>
</div>
<p v-if="metaOf(entry) && entry.kind !== 'comment'" class="mt-0.5 text-xs text-gray-500 dark:text-dark-400">
{{ metaOf(entry) }}
</p>
<!-- 这一行不是持有人自己结的:终止会把还挂在别人手上的待办一起结掉,档案照旧留在
他名下(他的已办列表要看得见这张单),可按按钮的是另一双手。不写出来,
看到的就永远是「主管终止了我的单」,而那是发起人自己按的。 -->
<p
v-if="operatorLine(entry)"
class="mt-0.5 flex flex-wrap items-center gap-1 text-xs text-gray-400 dark:text-dark-400"
>
<Icon name="ban" class="h-3 w-3 flex-shrink-0" />
{{ operatorLine(entry) }}
</p>
<p
v-if="entry.text"
class="mt-1.5 whitespace-pre-wrap rounded-lg bg-gray-50 px-3 py-2 text-gray-700 dark:bg-dark-900/60 dark:text-dark-200"
@ -352,10 +363,25 @@ function label(key: string): string {
return key ? t(key) : ''
}
function tagOf(entry: ApprovalRecordEntry): string {
return entry.tagKey ? t(entry.tagKey) : entry.tagText
}
/**
* 强制结单那句旁注:这一行由谁结掉的。
*
* 只有操作人与待办持有人不是同一个人时才有值(判据在 utils/approvalRecord 的
* ``forcedByName``)。终止单独说一句「由某某终止」——那是这一格最常撞上的场景,
* 也是唯一一句必须让人一眼看懂的话;其余强制结单跟着角标那句说法走。
*/
function operatorLine(entry: ApprovalRecordEntry): string {
const name = entry.operatorName
if (!name) return ''
if (entry.processingType === 'terminate') return t('task.recordTerminatedBy', { name })
const action = tagOf(entry)
return action ? t('task.recordActedBy', { name, action }) : t('task.recordActedByPlain', { name })
}
function time(entry: ApprovalRecordEntry): string {
return entry.time ? formatDateTimeToMinute(entry.time) : ''
}

View File

@ -0,0 +1,99 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import ExternalCheckPanel from './ExternalCheckPanel.vue'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import type { ExternalCheckState } from '@/types'
/**
* 这一块摆不摆的判据:这一单找不找得到一段闸门配置,而不是"接口通了"。
*
* 生产上没配外部核验的流程,手机上(和电脑上)也会白挂一块「外部核验 / 未提交 / 提交」,
* 点提交还被闸门当没这一回事——后端一直把 `configured` 发回来了,是这一层没认。
*/
const { getExternalCheck } = vi.hoisted(() => ({ getExternalCheck: vi.fn() }))
vi.mock('@/api', () => ({ checkAPI: { getExternalCheck } }))
function summary(over: Record<string, unknown> = {}) {
return {
id: 1,
provider: 'erp',
scene: 'invoice',
sceneLabel: '发票核验',
bizKey: 'BX-1',
revision: 1,
status: 'passed',
statusLabel: '已通过',
open: false,
verdict: '',
reason: '',
summary: '两张发票全部通过',
items: [],
checker: '',
checkerName: '',
checkedAt: '',
origin: '',
originLabel: '',
externalRef: '',
messageId: '',
filesHash: '',
fileCount: 2,
pollAttempts: 1,
nextPollAt: '',
activityName: '',
actorName: '',
createTime: '',
...over
}
}
function state(over: Partial<ExternalCheckState> = {}): ExternalCheckState {
return {
scene: 'invoice',
configured: true,
summary: null,
items: [],
fileCount: 0,
filesChanged: false,
gate: { mode: 'block', flag: '', activity: 'a-gm', canRefresh: false, canWithdraw: false, summary: '', item: { id: '', name: '', amount: '' } },
...over
} as ExternalCheckState
}
async function render(over: Partial<ExternalCheckState> = {}) {
getExternalCheck.mockResolvedValue(state(over))
const wrapper = mount(ExternalCheckPanel, {
props: { job: 'BX-20261103-0142' },
global: { plugins: [i18n] }
})
await flushPromises()
return wrapper
}
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
setActivePinia(createPinia())
getExternalCheck.mockReset()
})
describe('没配闸门的单子不摆外部核验这一块', () => {
it('configured=false 且没有结论:整块不出现', async () => {
const wrapper = await render({ configured: false, summary: null })
expect(wrapper.find('[data-test="external-check"]').exists()).toBe(false)
})
it('configured=true:照旧摆出来', async () => {
const wrapper = await render({ configured: true, summary: null })
expect(wrapper.find('[data-test="external-check"]').exists()).toBe(true)
})
it('闸门后来被撤了但真送过一次审:那句话还得留着给人看', async () => {
const wrapper = await render({ configured: false, summary: summary() as never })
const panel = wrapper.find('[data-test="external-check"]')
expect(panel.exists()).toBe(true)
expect(panel.text()).toContain('已通过')
})
})

View File

@ -1,5 +1,7 @@
<template>
<section v-if="state" class="card p-4 md:p-5" data-test="external-check">
<!-- 外层这一句只管类型收窄:读到过台账才可能有内容可摆;真摆不摆由 visible 判(没配闸门就不出现) -->
<template v-if="state">
<section v-if="visible" class="card p-4 md:p-5" data-test="external-check">
<div class="flex flex-wrap items-start justify-between gap-x-3 gap-y-2">
<div class="min-w-0">
<h3 class="flex items-center gap-2 text-sm font-semibold text-gray-900 dark:text-white">
@ -149,12 +151,15 @@
<p v-if="error" class="mt-2 text-xs leading-relaxed text-red-600">{{ error }}</p>
</section>
</template>
</template>
<script setup lang="ts">
/**
* 审批页 / 单据页上的「外部核验」面板:把台账念给人听,并提供四个动作。
*
* 摆不摆这一块的判据是**这一单找不找得到一段闸门配置**(`configured`),不是"接口通了"。
*
* 四个动作没有一个能改结论——送审只是把附件清单送出去,撤回只是请对方作废那一批,
* 重新核验是现问一次,应急放行改的也不是结论而是"这一次提交人背不背这个责任"。
* 判定发生在服务端提交链路(``service/gate.py``),这里挡住不了提交,也只负责说清
@ -199,6 +204,14 @@ const showItems = ref(true)
let timer = 0
const summary = computed(() => state.value?.summary ?? null)
/**
* 这一单压根没配核验闸门时,整块不摆。
*
* 后端一直把 `configured` 发回来了(`api/runtime.py` 里那句 `bool(cfg)`),只是这一层没认:
* 于是没配的流程也在单据上挂一块「外部核验 / 未提交 / 提交」,点下去还被闸门当没这一回事。
* 有结论(`summary`)时照旧摆——那是历史上真送过一次审的单,即使这一环的闸门被撤了也得留着给人看。
*/
const visible = computed(() => Boolean(state.value && (state.value.configured || state.value.summary)))
const headline = computed(() => summary.value?.sceneLabel || state.value?.scene || t('gate.panelTitle'))
const canRefresh = computed(() => Boolean(state.value?.gate?.canRefresh) && Boolean(summary.value))
const canWithdraw = computed(
@ -271,6 +284,8 @@ function schedule(next: ExternalCheckState | null): void {
window.clearTimeout(timer)
timer = 0
}
// 没配闸门时 summary 就是空的,这里天然不轮询;真有一段还没回来的结论,
// 哪怕这一环的闸门后来被撤了也照样得接着问,否则屏幕上那句「在等回传」永远不刷新
if (!next?.summary?.open || props.readonly) return
timer = window.setTimeout(() => {
void load()

View File

@ -162,6 +162,12 @@
/>
<p v-else class="text-sm text-gray-400">{{ t('start.formEmpty') }}</p>
</div>
<!-- 表单里那格「流程标题」就是标题的出处,改它等于改标题;保存前先把会换成哪一句
说出来,否则改完看见列表那一行没动,只会以为这一下压根没存上。 -->
<p v-if="titleNext" class="flex items-start gap-1.5 text-xs text-primary-600 dark:text-primary-300">
<Icon name="flag" class="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
<span>{{ t('monitor.intervene.dataTitleNext', { title: titleNext }) }}</span>
</p>
<div>
<p class="input-label">{{ t('monitor.intervene.reason') }}</p>
<TextArea v-model="reason" :rows="2" :placeholder="t('monitor.intervene.reasonPlaceholder')" />
@ -170,13 +176,19 @@
<button
type="button"
class="btn btn-primary btn-sm"
:disabled="!running || !changedKeys.length || busy"
:disabled="!running || !pendingKeys.length || busy"
@click="doFixData"
>
<Icon name="edit" class="mr-1 h-4 w-4" />{{ t('monitor.intervene.dataSave') }}
</button>
<span class="text-xs" :class="changedKeys.length ? 'text-primary-600' : 'text-gray-400'">
{{ changedKeys.length ? t('monitor.intervene.dataChanged', { count: changedKeys.length }) : t('monitor.intervene.dataNone') }}
<span class="text-xs" :class="pendingKeys.length ? 'text-primary-600' : 'text-gray-400'">
{{
changedKeys.length
? t('monitor.intervene.dataChanged', { count: changedKeys.length })
: titleDrift
? t('monitor.intervene.dataDrift')
: t('monitor.intervene.dataNone')
}}
</span>
</div>
</div>
@ -188,14 +200,30 @@
>
<p class="text-xs text-red-700 dark:text-red-300">{{ t('task.terminateConfirm') }}</p>
<div class="mt-2 flex items-center gap-2">
<Input v-model="reason" class="flex-1" :placeholder="t('task.terminateReasonPlaceholder')" />
<button type="button" class="btn btn-danger btn-sm" :disabled="busy" @click="confirmTerminate">
<Input
v-model="reason"
class="flex-1"
data-test="intervene-terminate-reason"
:placeholder="t('task.terminateReasonPlaceholder')"
/>
<button
type="button"
class="btn btn-danger btn-sm"
data-test="intervene-terminate"
:disabled="busy || !reason.trim()"
@click="confirmTerminate"
>
{{ t('task.terminate') }}
</button>
<button type="button" class="btn btn-ghost btn-sm" @click="terminateOpen = false">
{{ t('common.cancel') }}
</button>
</div>
<!-- 管理员这一路后端留了「管理员终止」那一句兜底,界面不许用它凑数:
终止会把别人手上的待办一起抹掉,档案里只剩四个字的话,事后谁也说不清为什么。 -->
<p class="mt-1 text-[11px] leading-relaxed text-red-600/80 dark:text-red-300/80">
{{ t('task.terminateReasonRequired') }}
</p>
</div>
</div>
@ -224,6 +252,7 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDebounceFn } from '@vueuse/core'
import BaseDialog from '@/components/common/BaseDialog.vue'
import Input from '@/components/common/Input.vue'
import TextArea from '@/components/common/TextArea.vue'
@ -255,6 +284,9 @@ const picker = ref('')
const moveTarget = ref('')
const draft = ref<Record<string, unknown>>({})
const terminateOpen = ref(false)
/** 改完表单之后标题会换成哪一句;口径在后端 titles.preview_refresh,与保存时引擎算的是同一段。 */
const titleNext = ref('')
let titleToken = 0
const running = computed(() => detail.value?.status === 'running')
const pending = computed<TaskItem[]>(() => detail.value?.tasks ?? [])
@ -294,14 +326,39 @@ const changedKeys = computed(() => {
)
})
/** 表单里那格「流程标题」叫什么:它的值就是单据标题的出处。 */
const titleKey = computed(() => {
const items = (formSchema.value?.fields ?? []) as { type?: string; key?: string }[]
return String(items.find((item) => item?.type === 'title')?.key ?? '')
})
/**
* 那一格写着另一句、单据标题却不是它:多半是「修正表单不同步标题」那一版留下的歪账。
* 这一格没人改动过,按钮却永远灰着,非改点别的才把名字对齐得回来,所以把它当成一项待修。
*/
const titleDrift = computed(() => {
const key = titleKey.value
const row = detail.value
if (!key || !row) return false
const value = String(draft.value[key] ?? '').trim()
return Boolean(value) && value !== String(row.title ?? '').trim()
})
/** 这一次要交上去的字段:改动过的那几项,加上等着对齐标题的那一格。 */
const pendingKeys = computed(() => {
const keys = [...changedKeys.value]
const key = titleKey.value
if (titleDrift.value && key && !keys.includes(key)) keys.push(key)
return keys
})
const panes = computed(() => [
{ key: 'handlers' as const, label: t('monitor.intervene.tabHandlers'), count: pending.value.length },
{ key: 'move' as const, label: t('monitor.intervene.tabMove'), count: 0 },
{ key: 'data' as const, label: t('monitor.intervene.tabData'), count: changedKeys.value.length }
{ key: 'data' as const, label: t('monitor.intervene.tabData'), count: pendingKeys.value.length }
])
async function reload() {
if (!props.job) return
titleToken++
titleNext.value = ''
loading.value = true
const value = await runAction(() => workAPI.getJob(props.job))
loading.value = false
@ -321,6 +378,8 @@ watch(
picked.value = []
picker.value = ''
terminateOpen.value = false
titleToken++
titleNext.value = ''
return
}
moveTarget.value = ''
@ -388,6 +447,25 @@ function transferAll() {
)
}
/**
* 「照现在这份改动存下去,标题会变成哪一句」。
*
* 只在真改了东西时问,答案也只说不动手:后端那句 changed 说的就是「这么交上去引擎会不会
* 重算标题」,既没改标题格、规则也没开自动重算时它是 false,界面不该给一句不兑现的预告。
* 问完发现数据又换过一轮(期间改了别的字段、或面板重新取了数)就把答案丢掉,
* 迟到的那一句不该贴在新一份数据下面。
*/
const askTitleNext = useDebounceFn(async () => {
const token = ++titleToken
if (!props.show || !running.value || !pendingKeys.value.length) {
titleNext.value = ''
return
}
const result = await workAPI.previewWorkTitle(props.job, draft.value).catch(() => null)
if (token !== titleToken) return
titleNext.value = result && result.changed ? result.title : ''
}, 400)
watch(draft, () => askTitleNext())
function doMove() {
const target = activityOptions.value.find((item) => item.value === moveTarget.value)
act(
@ -398,7 +476,7 @@ function doMove() {
function doFixData() {
const patch: Record<string, unknown> = {}
changedKeys.value.forEach((key) => {
pendingKeys.value.forEach((key) => {
patch[key] = draft.value[key]
})
act(

View File

@ -201,3 +201,70 @@ describe('多选月份的挑选方式(下拉多选 / 弹出框多选 / 平铺
expect(field.pickerStyle).toBeUndefined()
})
})
/**
* 「手机上不展示」这一档:手机上少摆的那几格得能在设计器里逐格定,
* 不然配表的人只能看着手机上短了一截的单子猜是谁干的。
*/
describe('手机上不展示这一档', () => {
function labelWith(wrapper: ReturnType<typeof inspector>['wrapper'], text: string) {
return wrapper.findAll('label').find((node) => node.text().includes(text))
}
it('普通格子有这一档,勾上就写进字段', async () => {
const { wrapper, field } = inspector({ key: 'code', label: '物料编码', type: 'text' })
await flushPromises()
const hit = labelWith(wrapper, '手机上不展示')
expect(hit).toBeTruthy()
await hit!.find('input').setValue(true)
expect(field.mobileHidden).toBe(true)
})
it('「标签页」那一格不给这一档:手机上那几节的段名就是照它认的', async () => {
const { wrapper } = inspector({
key: 'tabs_host',
label: '标签页',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '基本信息' },
{ key: 'tab_2', label: '发票信息' }
]
})
await flushPromises()
expect(labelWith(wrapper, '手机上不展示')).toBeFalsy()
// 「默认隐藏」那一档照旧在:整片藏起来这件事仍然配得了
expect(labelWith(wrapper, '默认隐藏')).toBeTruthy()
})
it('框选一片一次收掉:勾上手机上不展示,排版件与「标签页」不参与', async () => {
const cells = [
{ key: 'a', label: '字段A', type: 'text' },
{ key: 'b', label: '字段B', type: 'text' },
{ key: 'sec', label: '第一段', type: 'divider' },
{ key: 'tabs_host', label: '标签页', type: 'tabs', tabs: [{ key: 'tab_1', label: '基本信息' }, { key: 'tab_2', label: '发票' }] }
] as unknown as FormFieldDef[]
const i18n = createI18n({ legacy: false, locale: 'zh', messages: { zh } })
const wrapper = mount(FieldInspector, {
props: {
cells: cells.map((item, index) => ({ key: item.key, index, field: item, row: 1, col: index + 1, units: 6, alone: true })),
selectedKeys: cells.map((item) => item.key),
positionOf: () => '第 1 行'
},
global: { plugins: [i18n] }
})
await flushPromises()
const hide = wrapper.findAll('button').find((node) => node.text() === '手机上不展示')
expect(hide).toBeTruthy()
await hide!.trigger('click')
expect(cells[0].mobileHidden).toBe(true)
expect(cells[1].mobileHidden).toBe(true)
// 分隔条上没这一档,标签页藏了会把整张单的段名一起弄没
expect(cells[2].mobileHidden).toBeUndefined()
expect(cells[3].mobileHidden).toBeUndefined()
const show = wrapper.findAll('button').find((node) => node.text() === '手机上都展示')
await show!.trigger('click')
expect(cells[0].mobileHidden).toBe(false)
})
it('分隔条这类排版件本来就没有可见性开关', async () => {
const { wrapper } = inspector({ key: 'sec', label: '一、基本信息', type: 'divider' })
await flushPromises()
expect(labelWith(wrapper, '默认隐藏')).toBeFalsy()
expect(labelWith(wrapper, '手机上不展示')).toBeFalsy()
})
})

View File

@ -809,6 +809,20 @@
<Icon name="infoCircle" class="h-3.5 w-3.5 text-gray-400" />
</span>
</label>
<!-- 只影响手机版式:电脑上照旧摆着,手机上摘要与完整单据都不出现这一格。
「标签页」那一格不给这一档——手机版式的分节就是照着它认的,藏了它连段名都没了。 -->
<label v-if="mobileHideVisible" class="flex items-center gap-2">
<input
:checked="Boolean(field.field.mobileHidden)"
type="checkbox"
class="h-4 w-4 rounded"
@change="patch({ mobileHidden: ($event.target as HTMLInputElement).checked })"
/>
{{ t('form.mobileHiddenField') }}
<span class="flex items-center" :title="t('form.mobileHiddenFieldHint')">
<Icon name="infoCircle" class="h-3.5 w-3.5 text-gray-400" />
</span>
</label>
</div>
<TextArea
@ -827,6 +841,9 @@
<div class="flex flex-wrap gap-1.5">
<button type="button" class="btn btn-secondary btn-sm" @click="bulkPatch({ required: true })">{{ t('form.markRequired') }}</button>
<button type="button" class="btn btn-secondary btn-sm" @click="bulkPatch({ required: false })">{{ t('form.unmarkRequired') }}</button>
<!-- 三十几格的单子要在手机上收成几格,逐格点太累:框选一按就是一片 -->
<button type="button" class="btn btn-secondary btn-sm" @click="bulkMobile(true)">{{ t('form.bulkMobileHide') }}</button>
<button type="button" class="btn btn-secondary btn-sm" @click="bulkMobile(false)">{{ t('form.bulkMobileShow') }}</button>
</div>
</template>
</div>
@ -1020,6 +1037,8 @@ const LAYOUT_TYPES: string[] = ['divider', 'description', 'hidden']
/** 排版件和「隐藏域」本来就谈不上显不显示,那个开关只给真要在表单上占一格的字段。 */
const hideToggleVisible = computed(() => !LAYOUT_TYPES.includes(field.value?.field.type ?? ''))
/** 「手机上不展示」同一档判据,只是「标签页」那一格除外:它是手机版式的分节依据。 */
const mobileHideVisible = computed(() => hideToggleVisible.value && field.value?.field.type !== 'tabs')
/** 换字段类型时要清掉的展现配置:上一个类型的写法不该跟到新控件上。 */
const FORMAT_KEYS = ['numberFormat', 'precision', 'unit', 'uppercase', 'min', 'max', 'step'] as const
@ -1858,6 +1877,19 @@ function bulkPatch(values: Partial<FormFieldDef>) {
emit('patch')
}
/**
* 批量设「手机上不展示」:多选框里一片格子一次收掉。
*
* 排版件与「标签页」跳过——前者本来就上不了屏,后者是手机版式认分节名的依据,
* 把它藏了整张单就只剩一节「表单内容」。
*/
function bulkMobile(hidden: boolean) {
props.cells
.filter((cell) => props.selectedKeys.includes(cell.key))
.filter((cell) => !LAYOUT_TYPES.includes(cell.field.type) && !isTabsField(cell.field))
.forEach((cell) => Object.assign(cell.field, { mobileHidden: hidden }))
emit('patch')
}
function everyUnits(units: number): boolean {
const targets = props.cells.filter((cell) => props.selectedKeys.includes(cell.key))
return targets.length > 0 && targets.every((cell) => cell.units === units)

View File

@ -85,6 +85,12 @@
class="chip-position flex-shrink-0"
:title="t('form.hiddenFieldHint')"
>{{ t('form.hiddenBadge') }}</span>
<!-- 只在手机版式里隐身:不标出来,配表的人会以为手机上少摆的那格是程序丢的 -->
<span
v-if="cell.field.mobileHidden && !cell.field.hidden"
class="chip-position flex-shrink-0"
:title="t('form.mobileHiddenFieldHint')"
>{{ t('form.mobileHiddenBadge') }}</span>
<!-- 标题口径写在格子上:不点进去也知道这条流程的标题此刻怎么拼 -->
<span
v-if="cell.field.type === 'title'"

View File

@ -0,0 +1,182 @@
// @vitest-environment jsdom
/**
* 表单设计器里那个「手机端」面板。
*
* 盯三件最容易出事的地方:
*
* 1. **清单要对得上现在这张表**:排版件与标签页容器不列,删掉的格子不出现,新加的补在最后;
* 2. **改动当场交回画布**:面板没有"确定"这一步,顺序一改就得 emit,
* 否则关上门画布还是旧的,人以为配完了;
* 3. **上不上屏写的是格子上的那颗键**(``mobileHidden``),不是这份配置里的第二份开关——
* 两处各存一遍,早晚变成"属性面板勾了、手机端面板没勾"。
*/
import { beforeEach, describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import MobileLayoutPanel from './MobileLayoutPanel.vue'
import type { FormFieldDef, MobileLayout } from '@/types'
function field(over: Partial<FormFieldDef> & { key: string; type: FormFieldDef['type'] }): FormFieldDef {
return { label: over.key, ...over } as FormFieldDef
}
const FIELDS = [
field({ key: 'sec', label: '一、基本信息', type: 'divider' }),
field({ key: 'reason', label: '报销事由', type: 'textarea' }),
field({ key: 'amount', label: '报销金额', type: 'money' }),
field({ key: 'rows', label: '费用明细', type: 'table' }),
field({ key: 'gone', label: '内部编号', type: 'text', mobileHidden: true }),
field({ key: 'pages', label: '标签页', type: 'tabs', tabs: [{ key: 'tab_1', label: '费用报销基本信息' }] })
] as FormFieldDef[]
function open(layout: MobileLayout | null, over: Record<string, unknown> = {}) {
return mount(MobileLayoutPanel, {
props: { show: true, fields: FIELDS, layout, fallbackTitle: '费用报销基本信息', ...over },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true } }
})
}
function rowTexts(wrapper: ReturnType<typeof open>): string[] {
return wrapper.findAll('[data-test="mobile-layout-row"]').map((row) => row.text().replace(/\s+/g, ' '))
}
function lastUpdate(wrapper: ReturnType<typeof open>): MobileLayout {
return wrapper.emitted('update')!.at(-1)![0] as MobileLayout
}
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
describe('MobileLayoutPanel:清单上摆的是此刻这张表', () => {
it('分隔条与标签页容器不列,配过的顺序照搬,没配的补在最后', () => {
const wrapper = open({
enabled: true,
title: '费用报销基本信息',
fields: [{ key: 'amount', style: 'float' }, { key: 'reason' }]
})
const texts = rowTexts(wrapper)
// 配置里那两格在前(照配置的顺序),没配过的两格补在最后;分隔条与标签页容器不列
expect(texts.map((text) => text.match(/报销金额|报销事由|费用明细|内部编号|一、基本信息|标签页/)?.[0] ?? '')).toEqual([
'报销金额',
'报销事由',
'费用明细',
'内部编号'
])
// 那颗「不展示」的格子照样在清单上,不然面板打不开它
expect(texts.at(-1)).toContain('不展示')
})
it('开关没开时也给出整份清单,勾上开关就能立刻改', () => {
const wrapper = open(null)
expect(wrapper.find('[data-test="mobile-layout-row"]').exists()).toBe(false)
expect(wrapper.find('[data-test="mobile-layout-enable"]').attributes('checked')).toBeUndefined()
})
it('勾上开关:当场交回一份开了的配置,清单立刻出来', async () => {
const wrapper = open(null)
await wrapper.find('[data-test="mobile-layout-enable"]').setValue(true)
expect(lastUpdate(wrapper).enabled).toBe(true)
expect(rowTexts(wrapper)).toHaveLength(4)
})
it('这张表没有能上屏的格子时说一句,不留一片空白', () => {
const wrapper = mount(MobileLayoutPanel, {
props: { show: true, fields: [field({ key: 'sec', type: 'divider' })], layout: { enabled: true, fields: [] } },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true } }
})
expect(wrapper.find('[data-test="mobile-layout-empty"]').exists()).toBe(true)
})
})
describe('MobileLayoutPanel:改动当场交回画布', () => {
const LAYOUT: MobileLayout = {
enabled: true,
title: '费用报销基本信息',
showFullSheet: false,
fields: [{ key: 'amount', style: 'float' }, { key: 'reason' }, { key: 'rows', style: 'list' }]
}
/** 生产那张单的形状:标签页第二页整页让给外部系统。 */
const WITH_EMBED: FormFieldDef[] = [
FIELDS[1],
FIELDS[2],
field({
key: 'pages',
label: '标签页',
type: 'tabs',
tabs: [{ key: 'tab_1', label: '费用报销基本信息' }, { key: 'tab_2', label: '费用报销发票信息', kind: 'embed' }]
})
]
it('「标签页」里那一整页外部页面也在清单上,那颗开关记在配置里而不是格子上', async () => {
const wrapper = open(LAYOUT, { fields: WITH_EMBED })
const embed = wrapper.findAll('[data-test="mobile-layout-row"]').at(-1)!
// 名字取页签名,类型那一栏写「外部页面」,摆法只有「打开卡片」一档
expect(embed.text()).toContain('费用报销发票信息')
expect(embed.text()).toContain('外部页面')
expect(wrapper.find('[data-test="mobile-layout-embed-note"]').exists()).toBe(true)
// 它没有格子可以挂「手机上不展示」,所以勾它只动这份配置,不 emit patch
await wrapper.find('[data-test="mobile-layout-visible-pages#tab_2"]').trigger('click')
expect(wrapper.emitted('patch')).toBeUndefined()
const saved = lastUpdate(wrapper).fields?.find((row) => row.key === 'pages#tab_2')
expect(saved?.hidden).toBe(true)
expect(saved?.style).toBe('embed')
})
it('下移一格:交回去的数组顺序就是新的顺序', async () => {
const wrapper = open(LAYOUT)
await wrapper.find('[data-test="mobile-layout-down-amount"]').trigger('click')
expect(lastUpdate(wrapper).fields?.map((row) => row.key)).toEqual(['reason', 'amount', 'rows', 'gone'])
})
it('换摆法:只有那一格变,别的格子的设置原样带着', async () => {
const wrapper = open(LAYOUT)
const select = wrapper.findAll('[data-test="mobile-layout-row"]')[1].findComponent({ name: 'Select' })
await select.vm.$emit('update:modelValue', 'block')
const fields = lastUpdate(wrapper).fields ?? []
expect(fields.find((row) => row.key === 'reason')?.style).toBe('block')
expect(fields.find((row) => row.key === 'amount')?.style).toBe('float')
expect(fields.find((row) => row.key === 'rows')?.style).toBe('list')
})
it('点「展示 / 不展示」:写的是格子上的 mobileHidden,不动这份配置', async () => {
const wrapper = open(LAYOUT)
const patches = wrapper.emitted('patch')
expect(patches).toBeUndefined()
await wrapper.find('[data-test="mobile-layout-visible-reason"]').trigger('click')
expect(wrapper.emitted('patch')?.at(-1)).toEqual(['reason', { mobileHidden: true }])
expect(wrapper.emitted('update')).toBeUndefined()
// 关掉的那一行淡下去,但还在清单上——下一按就要能打开
expect(wrapper.find('[data-test="mobile-layout-visible-reason"]').text()).toContain('不展示')
})
it('节名与「完整单据」入口都写进配置', async () => {
const wrapper = open(LAYOUT)
await wrapper.find('[data-test="mobile-layout-title"] input').setValue(' ')
await wrapper.find('[data-test="mobile-layout-full"]').setValue(true)
const layout = lastUpdate(wrapper)
expect(layout.title).toBe('')
expect(layout.showFullSheet).toBe(true)
})
it('关掉总开关:配置留着但 enabled=false,顺序不丢', async () => {
const wrapper = open(LAYOUT)
await wrapper.find('[data-test="mobile-layout-enable"]').setValue(false)
const layout = lastUpdate(wrapper)
expect(layout.enabled).toBe(false)
expect(layout.fields?.map((row) => row.key)).toEqual(['amount', 'reason', 'rows'])
})
it('短名没改过就不存一份和字段标题一样的字:字段改名时手机上跟着改', async () => {
const wrapper = open(LAYOUT)
const alias = wrapper.findAll('[data-test="mobile-layout-row"]')[1].find('input[aria-label]')
await alias.setValue('事由')
await alias.trigger('change')
expect(lastUpdate(wrapper).fields?.find((row) => row.key === 'reason')?.label).toBe('事由')
await alias.setValue('报销事由')
await alias.trigger('change')
expect(lastUpdate(wrapper).fields?.find((row) => row.key === 'reason')?.label).toBeUndefined()
})
})

View File

@ -0,0 +1,310 @@
<template>
<BaseDialog
:show="show"
:title="t('mobile.layoutTitle')"
width="extra-wide"
close-on-click-outside
@close="emit('close')"
>
<p class="mb-3 text-xs leading-relaxed text-gray-500 dark:text-dark-400">{{ t('mobile.layoutIntro') }}</p>
<label class="mb-3 flex items-start gap-2 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<input
:checked="draft.enabled"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded"
data-test="mobile-layout-enable"
@change="toggle(($event.target as HTMLInputElement).checked)"
/>
<span class="min-w-0 flex-1">
<span class="block text-sm font-medium text-gray-900 dark:text-white">{{ t('mobile.layoutEnable') }}</span>
<span class="mt-0.5 block text-[11px] leading-relaxed text-gray-400 dark:text-dark-500">
{{ draft.enabled ? t('mobile.layoutFloatNote') : t('mobile.layoutOffHint') }}
</span>
</span>
</label>
<template v-if="draft.enabled">
<div class="mb-3 grid gap-3 sm:grid-cols-2">
<Input
v-model="draftTitle"
:label="t('mobile.layoutSection')"
:placeholder="fallbackTitle"
data-test="mobile-layout-title"
@update:model-value="commit"
/>
<label class="flex items-start gap-2 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600 sm:mt-6">
<input
:checked="draftFull"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded"
data-test="mobile-layout-full"
@change="toggleFull(($event.target as HTMLInputElement).checked)"
/>
<span class="min-w-0 flex-1">
<span class="block text-sm text-gray-900 dark:text-white">{{ t('mobile.layoutShowFull') }}</span>
<span class="mt-0.5 block text-[11px] leading-relaxed text-gray-400 dark:text-dark-500">{{ t('mobile.layoutShowFullHint') }}</span>
</span>
</label>
</div>
<p class="input-label mb-1">{{ t('mobile.layoutList') }}</p>
<div class="max-h-[46vh] overflow-y-auto rounded-xl border border-gray-200 dark:border-dark-600">
<p v-if="!rows.length" class="px-3 py-6 text-center text-[13px] text-gray-400" data-test="mobile-layout-empty">
{{ t('mobile.layoutEmpty') }}
</p>
<div
v-for="(row, index) in rows"
:key="row.key"
class="flex items-center gap-2 border-b border-gray-100 px-2.5 py-2 last:border-b-0 dark:border-dark-700"
:class="row.visible ? '' : 'opacity-60'"
data-test="mobile-layout-row"
>
<span class="num w-5 flex-shrink-0 text-center text-[11px] text-gray-400 dark:text-dark-500">{{ index + 1 }}</span>
<div class="min-w-0 flex-1">
<p class="flex min-w-0 items-center gap-1.5">
<span class="min-w-0 truncate text-[13px] font-medium text-gray-900 dark:text-dark-100">{{ row.label }}</span>
<span class="badge badge-gray flex-shrink-0 !text-[10px]">{{ row.typeText }}</span>
<span v-if="row.alwaysHidden" class="badge badge-gray flex-shrink-0 !text-[10px]">{{ t('form.hiddenField') }}</span>
</p>
<input
v-model="row.alias"
class="mt-1 w-full rounded border border-transparent bg-transparent px-0 py-0 text-[11px] text-gray-500 hover:border-gray-200 focus:border-primary-400 focus:outline-none dark:text-dark-400 dark:hover:border-dark-600"
:placeholder="t('mobile.layoutAliasPlaceholder')"
:aria-label="t('mobile.layoutAlias')"
@change="commit"
/>
</div>
<!-- 摆法那一栏窄,名字给短的,一句话说清的事挂在 tooltip 上 -->
<span class="w-[8.5rem] flex-shrink-0" :title="styleHint(row.style)">
<Select
v-if="row.styles.length > 1"
:model-value="row.style"
:options="row.styles"
@update:model-value="patchStyle(index, $event)"
/>
<span v-else class="block truncate text-right text-[11px] text-gray-400 dark:text-dark-500">
{{ row.styles[0]?.label }}
</span>
</span>
<button
type="button"
class="btn btn-sm flex-shrink-0"
:class="row.visible ? 'btn-secondary' : 'btn-ghost text-gray-400'"
:data-test="`mobile-layout-visible-${row.key}`"
@click="toggleVisible(index)"
>
<Icon :name="row.visible ? 'eye' : 'eyeOff'" class="h-3.5 w-3.5" />
{{ row.visible ? t('mobile.layoutShow') : t('mobile.layoutHide') }}
</button>
<span class="flex flex-shrink-0 items-center">
<button
type="button"
class="btn btn-ghost btn-sm !px-1.5"
:disabled="index === 0"
:title="t('mobile.layoutUp')"
:data-test="`mobile-layout-up-${row.key}`"
@click="move(index, -1)"
>
<Icon name="arrowUp" class="h-3.5 w-3.5" />
</button>
<button
type="button"
class="btn btn-ghost btn-sm !px-1.5"
:disabled="index === rows.length - 1"
:title="t('mobile.layoutDown')"
:data-test="`mobile-layout-down-${row.key}`"
@click="move(index, 1)"
>
<Icon name="arrowDown" class="h-3.5 w-3.5" />
</button>
</span>
</div>
</div>
<div class="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1">
<p class="text-[11px] text-gray-400 dark:text-dark-500" data-test="mobile-layout-stat">
{{ t('mobile.layoutStat', { shown: stat.shown, hidden: stat.hidden }) }}
</p>
<p class="min-w-0 flex-1 text-[11px] leading-relaxed text-gray-400 dark:text-dark-500">{{ t('mobile.layoutPermNote') }}</p>
</div>
<!-- 「标签页」里那一整页外部页面也在清单上:它不是格子,那颗开关记在这份配置里,
不写进格子身上(它压根没有格子),配表的人不该被这一点绊住 -->
<p v-if="hasEmbed" class="mt-1 text-[11px] leading-relaxed text-gray-400 dark:text-dark-500" data-test="mobile-layout-embed-note">
{{ t('mobile.layoutEmbedNote') }}
</p>
</template>
<template #footer>
<button type="button" class="btn btn-primary btn-sm" data-test="mobile-layout-done" @click="emit('close')">
{{ t('common.close') }}
</button>
</template>
</BaseDialog>
</template>
<script setup lang="ts">
/**
* 表单设计器里的「手机端」面板:一张表单独一份,只讲手机上那一屏。
*
* 为什么做成一张清单而不是往属性面板里再塞几栏:要配的是**顺序**,顺序是格子之间的事,
* 摊在 32 个属性面板里就没人能看出整张单子在手机上读起来是什么样。清单从上往下就是
* 手机上从上往下,上移下移两颗粒子改一格,配表的人不用猜。
*
* 只有两样东西住在这儿:顺序 / 摆法(这份配置 `layout.mobile`),和某一格上不上屏
* (写的还是格子上的 `mobileHidden`,与属性面板那颗「手机上不展示」同一个键,不分两家)。
* 每一改动都当场 `emit('update' | 'patch')` 交回画布,所以这边一改,画布旁边的预览、
* 未保存的小黄点、撤销栈全跟着走——不存在"点了确定才生效"那一档。
*/
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import BaseDialog from '@/components/common/BaseDialog.vue'
import Icon from '@/components/icons/Icon.vue'
import Input from '@/components/common/Input.vue'
import Select from '@/components/common/Select.vue'
import { mobileEntries, styleFor, styleOptionsFor } from '@/utils/mobileLayout'
import { fieldTypeLabel } from '@/utils/approverTargets'
import type { FormFieldDef, MobileFieldLayout, MobileFieldStyle, MobileLayout } from '@/types'
const props = defineProps<{
show: boolean
/** 这张表上的全部格子(含排版件),面板自己筛掉上不了屏的那几类 */
fields: FormFieldDef[]
/** 现存的配置;没配过时为 null,面板给一份草稿 */
layout: MobileLayout | null
/** 开关没打开时清单上第一格的兜底节名,写给占位符看 */
fallbackTitle?: string
}>()
const emit = defineEmits<{
close: []
/** 整份配置变了(顺序、摆法、节名、完整单据入口、开关) */
update: [layout: MobileLayout]
/** 某一格上不上屏:写回格子自己身上(`mobileHidden`),与属性面板那颗同源 */
patch: [key: string, values: Partial<FormFieldDef>]
}>()
interface Row {
/** 配置里那一条的键:普通格子是字段 key,外部页面那一页是 `格子key#页签key` */
key: string
label: string
typeText: string
field: FormFieldDef
style: MobileFieldStyle
styles: { value: MobileFieldStyle; label: string }[]
alias: string
visible: boolean
/** 整张流程都「默认隐藏」的那几格:这一档比手机端高,配了也不上屏,面板要说清楚 */
alwaysHidden: boolean
/** 「标签页」里那一整页外部页面:上不上屏记在配置的 hidden 上,不写回格子 */
embed: boolean
}
const { t } = useI18n()
const rows = ref<Row[]>([])
const draftTitle = ref('')
const draftFull = ref(false)
const draft = ref<MobileLayout>({ enabled: false })
watch(
() => props.show,
(open) => {
if (open) reset()
},
{ immediate: true }
)
/** 开门时按当前这张表把清单重算一遍:新加的格子补在最后,删掉的格子自然不见。 */
function reset() {
const layout = props.layout ?? { enabled: false }
draft.value = layout
draftTitle.value = String(layout.title ?? '')
draftFull.value = Boolean(layout.showFullSheet)
const entries = mobileEntries(layout.enabled ? layout : { ...layout, enabled: true }, props.fields)
rows.value = entries.map(({ field, entry, key, embed }) => ({
key,
label: String(field.label ?? field.key),
typeText: fieldTypeLabel(t, String(field.type)),
field,
style: styleFor(field, layout, entry),
styles: styleOptionsFor(field),
alias: String(entry.label ?? ''),
visible: embed ? !entry.hidden : !field.mobileHidden,
alwaysHidden: Boolean(field.hidden),
embed
}))
}
const stat = computed(() => {
const shown = rows.value.filter((row) => row.visible && !row.alwaysHidden).length
return { shown, hidden: rows.value.length - shown }
})
/** 这张表上有没有外部页面那一整页:有才多说那一句。 */
const hasEmbed = computed(() => rows.value.some((row) => row.embed))
/** 把清单压回配置:摆法与短名逐格存,上不上屏走 `patch`,两边各回各家。 */
function commit() {
const fields: MobileFieldLayout[] = rows.value.map((row) => {
const entry: MobileFieldLayout = { key: row.key, style: row.style }
const alias = row.alias.trim()
// 短名没改过就别存一份和字段标题一模一样的字:字段改名时手机上要跟着改
if (alias && alias !== row.label) entry.label = alias
// 外部页面那一格身上没地方挂「手机上不展示」,那颗开关只能存在这份配置里
if (row.embed && !row.visible) entry.hidden = true
return entry
})
emit('update', { ...draft.value, enabled: true, title: draftTitle.value.trim(), showFullSheet: draftFull.value, fields })
}
function toggle(on: boolean) {
// 先照现在这张表把清单重算一遍,再翻开关:先翻后算会让 reset 照着 props 把开关又按回去
reset()
draft.value = { ...draft.value, enabled: on }
// 关掉只翻开关:配好的顺序与摆法留在配置里,人只是想先看一眼自动归置那版
if (!on) emit('update', { ...draft.value, enabled: false })
else commit()
}
function toggleFull(on: boolean) {
draftFull.value = on
commit()
}
function patchStyle(index: number, style: unknown) {
const row = rows.value[index]
if (!row) return
row.style = String(style) as MobileFieldStyle
commit()
}
/** 那一档摆法在手机上是什么样:挂在 title 上,面板上不摊一堆说明。 */
function styleHint(style: MobileFieldStyle): string {
return t(`mobile.layoutStyleHint.${style}`)
}
function toggleVisible(index: number) {
const row = rows.value[index]
if (!row) return
row.visible = !row.visible
if (row.embed) {
commit()
return
}
emit('patch', row.key, { mobileHidden: !row.visible })
}
function move(index: number, delta: number) {
const at = index + delta
if (at < 0 || at >= rows.value.length) return
const list = [...rows.value]
const [moved] = list.splice(index, 1)
list.splice(at, 0, moved)
rows.value = list
commit()
}
</script>

View File

@ -810,7 +810,8 @@ const COLLAB_FLAGS: { key: string; labelKey: string }[] = [
{ key: 'allowComment', labelKey: 'process.allowComment' },
{ key: 'allowTransfer', labelKey: 'process.allowTransfer' },
{ key: 'allowRecall', labelKey: 'process.allowRecall' },
{ key: 'allowPress', labelKey: 'process.allowPress' }
{ key: 'allowPress', labelKey: 'process.allowPress' },
{ key: 'allowTerminate', labelKey: 'process.allowTerminate' }
]
const collabSwitches = computed(() => COLLAB_FLAGS.map((item) => ({ key: item.key, label: t(item.labelKey) })))

View File

@ -0,0 +1,208 @@
<template>
<div class="pb-2">
<!-- 顶栏:标题 + 几个数 + 搜索 + 刷新。桌面上那排筛选控件(流程、日期区间、批量、导出)
是为一次处理几十条单子准备的,手机上一次就批几条,摆进来比单子本身还占地方。 -->
<!-- -mx-4 抵掉 AppLayout 那个 main 的 p-4:顶栏要贴住屏幕两边,不能让内容内边距切出一道白缝。
顶栏自己再用 px-4 把标题和按钮收回来。 -->
<div
class="sticky top-0 z-10 -mx-4 border-b border-gray-100 bg-white/95 px-4 pb-2.5 pt-3 backdrop-blur dark:border-dark-700 dark:bg-dark-800/95"
>
<div class="flex items-center gap-2">
<h2 class="min-w-0 flex-1 truncate text-[17px] font-semibold text-gray-900 dark:text-white">
{{ title }}
<span v-if="total" class="num ml-1 text-[13px] font-normal text-gray-400 dark:text-dark-500">{{
total
}}</span>
</h2>
<button
v-if="showExpired"
type="button"
class="flex h-8 items-center gap-1 rounded-full border px-2.5 text-xs"
:class="
onlyExpired
? 'border-red-300 bg-red-50 text-red-600 dark:border-red-500/40 dark:bg-red-900/25 dark:text-red-300'
: 'border-gray-200 text-gray-500 dark:border-dark-600 dark:text-dark-400'
"
@click="emit('update:onlyExpired', !onlyExpired)"
>
<Icon name="clock" class="h-3.5 w-3.5" />{{ t('task.expired') }}
<span v-if="expired" class="num">{{ expired }}</span>
</button>
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-lg"
:aria-label="t('common.keyword')"
@click="searchOpen = !searchOpen"
>
<Icon name="search" class="h-[18px] w-[18px] text-gray-500 dark:text-dark-400" />
</button>
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-lg"
:aria-label="t('common.refresh')"
@click="emit('refresh')"
>
<Icon
name="refresh"
class="h-[18px] w-[18px] text-gray-500 dark:text-dark-400"
:class="loading ? 'animate-spin' : ''"
/>
</button>
</div>
<div v-if="searchOpen" class="mt-2 flex items-center gap-2 rounded-lg bg-gray-100 px-2.5 py-2 dark:bg-dark-700">
<Icon name="search" class="h-4 w-4 flex-shrink-0 text-gray-400" />
<input
class="min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-gray-400"
:value="keyword"
:placeholder="t('mobile.searchPlaceholder')"
@input="emit('update:keyword', ($event.target as HTMLInputElement).value)"
/>
<button v-if="keyword" type="button" :aria-label="t('common.reset')" @click="emit('update:keyword', '')">
<Icon name="x" class="h-4 w-4 text-gray-400" />
</button>
</div>
</div>
<div v-if="loading && !rows.length" class="space-y-2 pt-3" aria-hidden="true">
<div v-for="i in 4" :key="i" class="animate-pulse rounded-xl bg-white p-3.5 shadow-sm dark:bg-dark-800">
<div class="h-3.5 w-3/4 rounded bg-gray-200 dark:bg-dark-700"></div>
<div class="mt-2.5 h-3 w-2/5 rounded bg-gray-200 dark:bg-dark-700"></div>
<div class="mt-3.5 h-3 w-1/2 rounded bg-gray-100 dark:bg-dark-600"></div>
</div>
</div>
<EmptyState v-else-if="!rows.length" icon="inbox" :title="t('common.noData')" :description="emptyHint" />
<div v-else class="space-y-2 pt-3">
<button
v-for="row in rows"
:key="row.key"
type="button"
data-test="m-card"
class="relative block w-full overflow-hidden rounded-xl bg-white px-3.5 py-3.5 pl-4 text-left shadow-sm active:scale-[0.996] dark:bg-dark-800"
@click="emit('open', row.key)"
>
<span class="absolute inset-y-0 left-0 w-[3px]" :class="barClass(row.level)" aria-hidden="true"></span>
<span class="flex items-start gap-2">
<span
class="min-w-0 flex-1 text-[15px] font-semibold leading-snug text-gray-900 dark:text-white m-card-title"
>{{ row.title }}</span
>
<Icon name="chevronRight" class="mt-0.5 h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
</span>
<span
v-if="row.meta.length"
class="mt-2 flex flex-wrap items-center gap-x-1.5 text-xs text-gray-400 dark:text-dark-500"
>
<template v-for="(bit, index) in row.meta" :key="index">
<span v-if="index" class="text-gray-300 dark:text-dark-600">·</span>
<span>{{ bit }}</span>
</template>
</span>
<span
class="mt-2.5 flex flex-wrap items-center gap-1.5 border-t border-gray-100 pt-2.5 text-xs dark:border-dark-700"
>
<span v-for="badge in row.badges" :key="badge.text" class="badge" :class="badge.cls">{{ badge.text }}</span>
<span class="ml-auto flex-shrink-0 text-gray-500 dark:text-dark-400">{{ row.tail }}</span>
</span>
</button>
<!-- 到底部自己接着要,人不用回头找「下一页」那颗钮 -->
<p ref="sentinel" class="py-3 text-center text-xs text-gray-400" @click="emit('load-more')">
<span v-if="loading">{{ t('common.loading') }}</span>
<span v-else-if="finished" class="text-gray-300 dark:text-dark-600">{{ t('mobile.noMore') }}</span>
<span v-else>{{ t('mobile.loadMore') }}</span>
</p>
</div>
</div>
</template>
<script setup lang="ts">
/**
* 手机上「一串单子」的样子:一张卡三行,左边一道颜色说急不急,整张卡都是点击区。
*
* 它是个纯版式组件,不自己打接口:数据、分页、筛选状态都由列表页交下来
* (views/oa/TodoListView.vue),所以手机上看到的那几条和电脑上永远是同几条,
* 不会出现「手机上少一条因为那边自己查了一遍」。待办、已办、抄送哪个列表都要用,
* 各自把行喂进来即可。
*/
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import EmptyState from '@/components/common/EmptyState.vue'
export interface MobileCardRow {
key: string
title: string
meta: string[]
badges: { text: string; cls: string }[]
tail: string
/** 急不急:超时红、快到期黄,扫一眼就知道先批哪条 */
level?: 'danger' | 'warn' | ''
}
const props = withDefaults(
defineProps<{
title: string
rows: MobileCardRow[]
loading?: boolean
finished?: boolean
total?: number
expired?: number
keyword?: string
onlyExpired?: boolean
emptyHint?: string
/** 「只看超时」那颗钮:只有待办有超时这回事,已办、待阅摆上去是废按钮。 */
showExpired?: boolean
}>(),
{
loading: false,
finished: false,
total: 0,
expired: 0,
keyword: '',
onlyExpired: false,
emptyHint: '',
showExpired: true
}
)
const emit = defineEmits<{
open: [key: string]
'load-more': []
refresh: []
'update:keyword': [value: string]
'update:onlyExpired': [value: boolean]
}>()
const { t } = useI18n()
const searchOpen = ref(Boolean(props.keyword))
const sentinel = ref<HTMLElement | null>(null)
let watcher: IntersectionObserver | null = null
onMounted(() => {
// 滚到底自己接着要:手机上没有分页条,让人点「下一页」是很别扭的事
if (typeof IntersectionObserver !== 'function') return
watcher = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting) && !props.loading && !props.finished) emit('load-more')
})
if (sentinel.value) watcher.observe(sentinel.value)
})
onBeforeUnmount(() => watcher?.disconnect())
function barClass(level?: MobileCardRow['level']) {
if (level === 'danger') return 'bg-red-500'
if (level === 'warn') return 'bg-amber-500'
return 'bg-transparent'
}
</script>
<style scoped>
/* 标题最多两行:一条报销单的名字能写四十个字,不夹一下整张卡就散了 */
.m-card-title {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@ -0,0 +1,130 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import type { TaskCompletedItem } from '@/types'
import MobileFlow from './MobileFlow.vue'
/**
* 手机上那条流转时间线的三条底线:只摆最近几步、发起那一行不许被收掉、
* 「等谁处理」与单号还在。数据口径本身由 utils/approvalRecord 的测试管,
* 这一份只管摆法。
*/
const START = {
activity: '提交',
person: '李明',
unit: '软件开发事业部',
identity: 'p-1',
time: '2026-11-01 09:00:00'
}
const PENDING = [{ activity_name: '财务复核', identity_name: '陈妮' }]
const LONG = '发票已经逐张核过一遍,其中两程的打车票缺行程单,请补齐之后再走下一环;下月出行记得提前定额度,谢谢配合。'
function step(n: number): TaskCompletedItem {
return {
id: `done-${n}`,
activity_name: `第${n}环`,
activity: `a-${n}`,
identity_name: `审批人${n}`,
identity: `p-${n}`,
route_name: '同意',
opinion: n === 6 ? LONG : '同意',
completed_time: `2026-11-02 10:0${n}:00`,
status: 'completed',
attachments: [],
form_changes: []
} as unknown as TaskCompletedItem
}
async function render(options: { count?: number; canComment?: boolean } = {}) {
const count = options.count ?? 6
const pinia = createPinia()
setActivePinia(pinia)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/todo/:id', component: { template: '<div />' } }]
})
await router.push('/todo/task-1')
await router.isReady()
const wrapper = mount(MobileFlow, {
props: {
items: Array.from({ length: count }, (_, index) => step(index + 1)),
pending: PENDING,
start: START,
serial: 'BX-20261103-0142',
canComment: options.canComment ?? true
},
global: {
plugins: [router, pinia, i18n],
stubs: {
teleport: true,
Teleport: true,
AttachmentGallery: true,
PeoplePicker: true,
OpinionComposer: true,
ConfirmDialog: true
}
}
})
await flushPromises()
return wrapper
}
const rows = (wrapper: Awaited<ReturnType<typeof render>>) => wrapper.findAll('ol > li')
const titles = (wrapper: Awaited<ReturnType<typeof render>>) => rows(wrapper).map((row) => row.text())
describe('手机上的流转时间线', () => {
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
it('默认只摆最近三步,发起那一行永远留着', async () => {
const wrapper = await render({ count: 6 })
const text = titles(wrapper)
expect(text).toHaveLength(4)
expect(text[0]).toContain('提交')
expect(text[0]).toContain('李明')
expect(text.map((one) => one.includes('第6环'))).toEqual([false, false, false, true])
expect(wrapper.text()).not.toContain('第1环')
expect(wrapper.text()).not.toContain('第3环')
})
it('「展开更早」把剩下的补齐,钮跟着收掉', async () => {
const wrapper = await render({ count: 6 })
const earlier = wrapper.find('[data-test="m-flow-earlier"]')
expect(earlier.text()).toBe('展开更早 3 条')
await earlier.trigger('click')
expect(rows(wrapper)).toHaveLength(7)
expect(wrapper.text()).toContain('第1环')
expect(wrapper.find('[data-test="m-flow-earlier"]').exists()).toBe(false)
})
it('步数没超过三就不该有那颗钮', async () => {
const wrapper = await render({ count: 2 })
expect(wrapper.find('[data-test="m-flow-earlier"]').exists()).toBe(false)
expect(rows(wrapper)).toHaveLength(3)
})
it('卡在谁手上与单号都还在,批注也是从这条线上走', async () => {
const wrapper = await render()
expect(wrapper.text()).toContain('财务复核')
expect(wrapper.text()).toContain('陈妮')
expect(wrapper.text()).toContain('BX-20261103-0142')
await wrapper.find('[data-test="m-flow-comment"]').trigger('click')
expect(wrapper.find('[data-test="m-comment-sheet"]').exists() || wrapper.text().includes('批注')).toBe(true)
})
it('意见先给两行,超过一句长话才给展开', async () => {
const wrapper = await render()
const more = wrapper.findAll('[data-test="m-flow-more"]')
// 只有第 6 环那条写了长意见,别处的「同意」不该多一颗钮
expect(more).toHaveLength(1)
expect(more[0].text()).toBe('展开')
await more[0].trigger('click')
expect(more[0].text()).toBe('收起')
})
})

View File

@ -0,0 +1,399 @@
<template>
<div class="text-[13px]" data-test="m-flow">
<!-- 手机上的一条流转:竖着把这张单子说过做过的每一步走完。
桌面上那条记录带内层滚动、编号、部门、耗时和一整个批注表单,摊在 390px 上
比单子本身还长。这一版只留四件事:谁、在哪一步、什么时候、说了什么,
以及现在卡在谁手上——剩下的都在「展开更早」和折叠里。 -->
<ol v-if="rows.length">
<li v-for="row in visibleRows" :key="row.entry.key" class="flex gap-2.5">
<!-- 轨道:一个点加一段竖线。红=这一环没批过去,绿=批过去了,空心=还没轮到 -->
<span class="flex w-4 flex-shrink-0 flex-col items-center">
<span
class="mt-1.5 h-2.5 w-2.5 flex-shrink-0 rounded-full ring-2 ring-white dark:ring-dark-800"
:class="dotClass(row.entry)"
></span>
<span v-if="!row.tail" class="w-px flex-1" :class="railClass(row.entry)"></span>
</span>
<div class="min-w-0 flex-1" :class="row.tail ? 'pb-1' : 'pb-4'">
<div class="flex items-start gap-2">
<p class="min-w-0 flex-1 text-[14px] font-medium leading-snug text-gray-900 dark:text-white">
{{ titleOf(row.entry) }}
</p>
<span v-if="tagOf(row.entry)" class="badge flex-shrink-0" :class="row.entry.tagClass">{{ tagOf(row.entry) }}</span>
<button
v-if="row.entry.kind === 'comment' && row.entry.mine"
type="button"
class="flex-shrink-0 p-0.5 text-gray-300 dark:text-dark-600"
:aria-label="t('common.delete')"
@click="removing = row.entry.id"
>
<Icon name="trash" class="h-3.5 w-3.5" />
</button>
</div>
<p v-if="metaOf(row.entry)" class="mt-0.5 truncate text-[12px] text-gray-400 dark:text-dark-500">
{{ metaOf(row.entry) }}
</p>
<!-- 意见:两行读完,长了才给展开。手机上没人愿意为一句「同意」划半屏 -->
<div v-if="row.entry.text" class="mt-1.5 rounded-lg bg-gray-50 px-3 py-2 dark:bg-dark-900/60">
<p
class="whitespace-pre-wrap leading-relaxed text-gray-700 dark:text-dark-200"
:class="isOpen(row.entry.key) ? '' : 'line-clamp-2'"
>
{{ row.entry.text }}
</p>
<button
v-if="row.entry.text.length > 46"
type="button"
class="mt-1 text-[12px] text-primary-600 dark:text-primary-400"
data-test="m-flow-more"
@click="toggle(row.entry.key)"
>
{{ isOpen(row.entry.key) ? t('mobile.flowCollapse') : t('mobile.flowExpand') }}
</button>
</div>
<!-- 改过的格子:默认收成一行「改了 2 处」,改单不许是无声的,点开就是原值与新值 -->
<button
v-if="row.entry.formChanges.length"
type="button"
class="mt-1.5 flex w-full items-center gap-1.5 rounded-lg bg-amber-50 px-3 py-2 text-left text-[12px] text-amber-700 dark:bg-amber-900/20 dark:text-amber-300"
@click="toggle(changesKey(row.entry))"
>
<Icon name="edit" class="h-3.5 w-3.5 flex-shrink-0" />
<span class="flex-1">{{ t('task.formChanged') }} · {{ t('mobile.fieldCount', { count: row.entry.formChanges.length }) }}</span>
<Icon name="chevronRight" class="h-3.5 w-3.5 flex-shrink-0" :class="isOpen(changesKey(row.entry)) ? 'rotate-90' : ''" />
</button>
<div v-if="isOpen(changesKey(row.entry))" class="mt-1 space-y-1 rounded-lg bg-amber-50/70 px-3 py-2 text-[12px] text-amber-800 dark:bg-amber-900/20 dark:text-amber-200">
<p v-for="change in row.entry.formChanges" :key="change.key">
{{ t('task.formChangeLine', { label: change.label, before: change.before, after: change.after }) }}
</p>
</div>
<!-- 随意见贴的截图与文件:一行「附件 2」,点开才是缩略图 -->
<button
v-if="row.entry.attachments.length"
type="button"
class="mt-1.5 flex items-center gap-1.5 text-[12px] text-gray-400 dark:text-dark-500"
@click="toggle(filesKey(row.entry))"
>
<Icon name="paperclip" class="h-3.5 w-3.5" />
{{ t('mobile.flowFiles', { count: row.entry.attachments.length }) }}
<Icon name="chevronRight" class="h-3 w-3" :class="isOpen(filesKey(row.entry)) ? 'rotate-90' : ''" />
</button>
<AttachmentGallery v-if="isOpen(filesKey(row.entry))" :items="row.entry.attachments" />
<p
v-if="row.entry.kind === 'comment' && row.entry.mentions.length"
class="mt-1 text-[12px] text-gray-400 dark:text-dark-500"
>
@ {{ row.entry.mentions.map((one) => personText(one)).join('、') }}
</p>
</div>
</li>
</ol>
<p v-else class="py-6 text-center text-[13px] text-gray-400 dark:text-dark-500">{{ t('task.recordEmpty') }}</p>
<!-- 更早的记录:批十单的人只关心最近那两步,第一次看这张单的人才需要全程 -->
<button
v-if="hiddenSteps"
type="button"
class="-mt-1 mb-3 flex w-full items-center justify-center gap-1 rounded-xl border border-gray-200 py-2.5 text-[13px] text-gray-500 active:bg-gray-50 dark:border-dark-600 dark:text-dark-400 dark:active:bg-dark-800"
data-test="m-flow-earlier"
@click="showEarlier = true"
>
<Icon name="chevronUp" class="h-4 w-4" />
{{ t('mobile.flowEarlier', { count: hiddenSteps }) }}
</button>
<!-- 此刻卡在谁手上 -->
<div
v-if="waiting"
class="mb-3 flex items-center gap-2 rounded-xl border border-primary-200 bg-primary-50 px-3.5 py-3 text-[13px] text-primary-800 dark:border-primary-500/30 dark:bg-primary-900/20 dark:text-primary-100"
>
<Icon name="clock" class="h-4 w-4 flex-shrink-0" />
<span class="min-w-0 flex-1">{{ waiting }}</span>
</div>
<div class="space-y-2">
<button
v-if="canComment"
type="button"
class="flex w-full items-center gap-2 rounded-xl bg-gray-50 px-3.5 py-3 text-left text-[13px] text-gray-600 active:bg-gray-100 dark:bg-dark-700 dark:text-dark-300"
data-test="m-flow-comment"
@click="composerOpen = true"
>
<Icon name="chatBubble" class="h-4 w-4" />{{ t('task.commentAdd') }}
<span v-if="comments.length" class="num ml-auto opacity-70">{{ comments.length }}</span>
</button>
<button
v-if="hasSystemEvents"
type="button"
class="flex w-full items-center gap-2 rounded-xl px-3.5 py-2 text-left text-[12px] text-gray-400 dark:text-dark-500"
@click="showAll = !showAll"
>
<Icon name="bolt" class="h-3.5 w-3.5" />
<span>{{ t('task.recordEvents') }}</span>
<span class="ml-auto opacity-75">{{ showAll ? t('mobile.flowOn') : t('mobile.flowOff') }}</span>
</button>
<p v-if="serial" class="num pt-1 text-center text-[11px] text-gray-300 dark:text-dark-600">
{{ t('work.serial') }} {{ serial }}
</p>
</div>
<!-- 批注:正文、随附文件、@ 谁、要不要同时通知——与桌面那一份同样的四样,
只是搬到底部弹层里写:手机上那块输入框该在拇指底下,不该在屏幕当中。 -->
<MobileSheet :show="composerOpen" test="m-flow-sheet" :title="t('task.commentAdd')" @close="closeComposer">
<div class="pb-1">
<OpinionComposer
v-if="composerOpen"
ref="editor"
v-model="draft"
purpose="comment"
:placeholder="t('task.commentPlaceholder')"
:hint="t('task.commentComposerHint')"
:busy="busy"
:min-height="96"
:draft-key="draftKey"
auto-focus
show-submit
show-cancel
:submit-text="t('task.commentSend')"
@submit="onSubmit"
@cancel="closeComposer"
>
<template #recipients>
<button
type="button"
class="flex items-center gap-1 text-xs text-gray-500 dark:text-dark-400"
@click="mentionOpen = !mentionOpen"
>
<Icon name="user" class="h-3.5 w-3.5" />
<span>{{ t('task.commentMention') }}</span>
<span v-if="mentions.length" class="badge badge-primary ml-0.5">{{ mentions.length }}</span>
<Icon :name="mentionOpen ? 'chevronUp' : 'chevronDown'" class="h-3 w-3" />
</button>
<div v-if="mentionOpen" class="mt-2 space-y-2">
<PeoplePicker v-model="mentions" />
<label class="flex items-center gap-2 text-[13px] text-gray-500 dark:text-dark-400">
<input v-model="mentionAction" type="checkbox" class="h-3.5 w-3.5 rounded" />
{{ t('task.commentMentionAction') }}
</label>
</div>
</template>
</OpinionComposer>
</div>
</MobileSheet>
<ConfirmDialog
:show="removing !== ''"
:title="t('common.delete')"
:message="t('task.commentDeleteConfirm')"
danger
@confirm="confirmRemove"
@cancel="removing = ''"
/>
</div>
</template>
<script setup lang="ts">
/**
* 手机上的一条流转时间线。
*
* 数据口径与桌面完全同一份:entries 由 utils/approvalRecord 的 buildApprovalRecord 算,
* 这里只换摆法——去掉内层滚动(手机上页头页脚已经吃掉两成屏高,再套一层滚动区等于把
* 内容埋进抽屉)、去掉编号与部门、意见默认两行、附件与改单记录折成一行、更早的记录
* 收成一颗「展开更早」。批注也照旧挂在这条线上,不另开页签。
*/
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import AttachmentGallery from '@/components/oa/AttachmentGallery.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
import OpinionComposer from '@/components/oa/OpinionComposer.vue'
import PeoplePicker from '@/components/oa/PeoplePicker.vue'
import MobileSheet from './MobileSheet.vue'
import { formatDateTimeToMinute } from '@/utils/format'
import { personText } from '@/utils/personLabel'
import {
buildApprovalRecord,
durationTrail,
filterSystemLogs,
pendingTrail,
PENDING_NEXT,
type ApprovalRecordEntry,
type ApprovalStartLike,
type FlowRouteLike,
type PendingLike,
type RecordCommentPayload
} from '@/utils/approvalRecord'
import type { ComposerPayload, TaskCompletedItem, WorkComment, WorkLogItem } from '@/types'
const props = withDefaults(
defineProps<{
items: TaskCompletedItem[]
routes?: FlowRouteLike[]
pending?: PendingLike[]
start?: ApprovalStartLike | null
comments?: WorkComment[]
logs?: WorkLogItem[]
myIdentity?: string
canComment?: boolean
busy?: boolean
draftKey?: string
/** 单号:桌面摆在页头,手机上页头只留标题,这一串落在这里,要查还能查到 */
serial?: string
}>(),
{
routes: () => [],
pending: () => [],
start: null,
comments: () => [],
logs: () => [],
myIdentity: '',
canComment: false,
busy: false,
draftKey: '',
serial: ''
}
)
const emit = defineEmits<{
comment: [payload: RecordCommentPayload]
remove: [id: string]
}>()
const { t } = useI18n()
/** 默认只摆最近这几步;第一次看这张单的人自己点「展开更早」。 */
const RECENT = 3
const showEarlier = ref(false)
const showAll = ref(false)
const composerOpen = ref(false)
const mentionOpen = ref(false)
const mentionAction = ref(false)
const draft = ref('')
const mentions = ref<string[]>([])
const removing = ref('')
const editor = ref<InstanceType<typeof OpinionComposer> | null>(null)
/** 展开过的意见 / 改单 / 附件:按 key 记,换一张单子不跟着串。 */
const open = ref<Set<string>>(new Set())
const entries = computed(() =>
buildApprovalRecord({
items: props.items,
start: props.start,
comments: props.comments,
logs: props.logs,
routes: props.routes,
myIdentity: props.myIdentity,
withSystemEvents: showAll.value
})
)
const waiting = computed(() => {
const hit = pendingTrail(props.pending)
return hit ? t(hit.key, hit.params) : ''
})
const hasSystemEvents = computed(() => filterSystemLogs(props.logs).length > 0)
const rows = computed(() =>
entries.value.map((entry, index) => ({
entry,
// 末尾还挂着「等谁处理」时,最后一条不算尾,竖线要接到那一行上去
tail: index === entries.value.length - 1 && !waiting.value
}))
)
/** 一条流转里哪些是"走过的一步":发起与审批算,批注与引擎事件不算。 */
function isStep(entry: ApprovalRecordEntry): boolean {
return entry.kind === 'start' || entry.kind === 'approval' || entry.kind === 'skip'
}
const visibleRows = computed(() => {
const all = rows.value
if (showEarlier.value) return all
const steps = all.filter((row) => isStep(row.entry))
if (steps.length <= RECENT) return all
const keep = new Set(steps.slice(-RECENT).map((row) => row.entry.key))
// 发起那一行是这张单的开头,收着反而说不清,永远留着
all.forEach((row) => {
if (row.entry.kind === 'start') keep.add(row.entry.key)
})
return all.filter((row) => keep.has(row.entry.key))
})
const hiddenSteps = computed(() => rows.value.length - visibleRows.value.length)
function isOpen(key: string): boolean {
return open.value.has(key)
}
function toggle(key: string) {
const next = new Set(open.value)
if (next.has(key)) next.delete(key)
else next.add(key)
open.value = next
}
function changesKey(entry: ApprovalRecordEntry): string {
return `${entry.key}:changes`
}
function filesKey(entry: ApprovalRecordEntry): string {
return `${entry.key}:files`
}
function dotClass(entry: ApprovalRecordEntry): string {
if (entry.tone === 'danger') return 'bg-red-500'
if (entry.tone === 'success') return 'bg-green-500'
return entry.kind === 'approval' || entry.kind === 'skip' ? 'bg-gray-300 dark:bg-dark-600' : 'bg-primary-500'
}
function railClass(entry: ApprovalRecordEntry): string {
return entry.tone === 'danger' ? 'bg-red-200 dark:bg-red-900/60' : 'bg-gray-200 dark:bg-dark-700'
}
function titleOf(entry: ApprovalRecordEntry): string {
if (entry.kind === 'system') return entry.titleKey ? t(entry.titleKey) : ''
return entry.title || (entry.titleKey ? t(entry.titleKey) : '')
}
function tagOf(entry: ApprovalRecordEntry): string {
if (entry.kind === 'comment') return t('task.comment')
return entry.tagKey ? t(entry.tagKey) : entry.tagText
}
function metaOf(entry: ApprovalRecordEntry): string {
const time = entry.time ? formatDateTimeToMinute(entry.time) : ''
if (entry.kind === 'comment') return [entry.handler, time].filter(Boolean).join(' · ')
if (entry.kind === 'system') return [entry.fromName, entry.toName].filter(Boolean).join(' → ')
if (entry.kind === 'skip') return ''
// 部门在手机上不占这一行:抬头说过发起人是谁,审批人的部门对批单子没帮助
const hit = durationTrail(entry.durationSeconds)
return [entry.handler, time, hit ? t(hit.key, hit.params) : ''].filter(Boolean).join(' · ')
}
function onSubmit(payload: ComposerPayload) {
emit('comment', { ...payload, mentions: mentions.value, mentionAction: mentionAction.value })
}
/** 批注发出去之后由调用方收:正文、随附文件、@ 的人和草稿一起清掉。 */
function resetComposer() {
editor.value?.reset()
draft.value = ''
mentions.value = []
mentionAction.value = false
mentionOpen.value = false
}
function closeComposer() {
composerOpen.value = false
resetComposer()
}
function confirmRemove() {
emit('remove', removing.value)
removing.value = ''
}
// PENDING_NEXT 只是「这一步的落点就是当前等待」的哨兵值,界面上由 waiting 那一行说
void PENDING_NEXT
</script>
defineExpose({ reset: resetComposer })

View File

@ -0,0 +1,35 @@
<template>
<div class="overflow-hidden rounded-xl bg-white shadow-sm dark:bg-dark-800" :class="tone">
<button
type="button"
class="flex w-full items-center gap-2 px-3.5 py-3 text-left"
:aria-expanded="open"
@click="open = !open"
>
<Icon v-if="icon" :name="icon" class="h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
<span class="min-w-0 flex-1 truncate text-sm font-semibold text-gray-900 dark:text-white">{{ title }}</span>
<span v-if="note" class="flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">{{ note }}</span>
<Icon name="chevronRight" class="h-4 w-4 flex-shrink-0 text-gray-400 transition-transform dark:text-dark-500" :class="open ? 'rotate-90' : ''" />
</button>
<div v-show="open" class="border-t border-gray-100 dark:border-dark-700"><slot /></div>
</div>
</template>
<script setup lang="ts">
/**
* 折叠块:手机上「默认收起、点了才展开」的唯一实现。
*
* 一张 47 个字段的单子全摊开是六屏,领导真正要看的就两三样。折叠的粒度按流程设计里
* 本来就有的分隔条走(divider 字段就是分节标题),不额外发明一层「移动分组」配置——
* 设计器里改一分组,手机上跟着变,不会出现桌面改了手机上没改。
*/
import { ref, watch } from 'vue'
import Icon from '@/components/icons/Icon.vue'
type IconName = InstanceType<typeof Icon>['$props']['name']
const props = defineProps<{ title: string; note?: string; icon?: IconName; defaultOpen?: boolean; tone?: string }>()
const open = ref(Boolean(props.defaultOpen))
// 换了另一张单子(折叠状态被用户动过)时分节数可能变了,跟着重置一次
watch(() => props.title, () => { open.value = Boolean(props.defaultOpen) })
</script>

View File

@ -0,0 +1,125 @@
// @vitest-environment jsdom
import { beforeAll, describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import MobileFormReader from './MobileFormReader.vue'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import { expenseData, expenseSchema } from './mobileFixtures'
import type { FormFieldDef, FormSchema } from '@/types'
beforeAll(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
function field(over: Partial<FormFieldDef> & { key: string; type: FormFieldDef['type'] }): FormFieldDef {
return { label: over.key, ...over } as FormFieldDef
}
/** 生产上那张费用报销单的形状:一页格子 + 一页外部系统 */
function tabsSchema(): FormSchema {
return {
fields: [
field({
key: 'tabs_host',
label: '标签页',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '费用报销基本信息' },
{ key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }
],
tabsMode: 'collapse'
}),
field({ key: 'reason', label: '报销事由', type: 'textarea', tab: 'tab_1' }),
field({ key: 'city', label: '目的地', type: 'text', tab: 'tab_1' }),
field({ key: 'internal_no', label: '内部流转号', type: 'text', tab: 'tab_1', mobileHidden: true }),
field({ key: 'invoice_no', label: '发票号', type: 'text', tab: 'tab_2' })
]
}
}
const global = {
plugins: [i18n],
stubs: {
teleport: true,
Teleport: true,
AttachmentGallery: { props: ['items'], template: '<div data-test="gallery-stub">{{ items.length }}</div>' },
EmbedFrame: { props: ['field', 'slotKey'], template: '<div data-test="embed-stub">{{ field.key }}|{{ slotKey }}</div>' }
}
}
/** MobileFold 是 v-show 收折的,按祖先的 display 过滤一次才算"屏幕上看得见" */
function visibleText(wrapper: ReturnType<typeof mount>): string {
return wrapper
.findAll('[data-test="m-reader-row"], [data-test="m-reader-table"], [data-test="m-reader-media"], [data-test="embed-stub"]')
.filter((node) => {
let el: HTMLElement | null = node.element
while (el) {
if ((el.getAttribute('style') || '').includes('display: none')) return false
el = el.parentElement
}
return true
})
.map((node) => node.text().replace(/\s+/g, ' '))
.join('\n')
}
describe('手机上「完整单据」那一屏', () => {
it('按页签分节,外部页面那一节给一张卡片而不是内嵌', () => {
const wrapper = mount(MobileFormReader, {
props: { schema: tabsSchema(), data: { reason: '出差', city: '北京', internal_no: 'N-9', invoice_no: 'FP-1' }, job: 'BX-1', activity: 'a-gm' },
global
})
const titles = wrapper.findAll('[aria-expanded]').map((node) => node.text())
expect(titles).toEqual(['费用报销基本信息2 项', '费用报销发票信息外部页面'])
expect(visibleText(wrapper)).toContain('报销事由')
expect(visibleText(wrapper)).toContain('tabs_host|tabs_host#tab_2')
// 压在外部页面那一页上的格子不重复摆一遍
expect(visibleText(wrapper)).not.toContain('发票号')
})
it('勾了「手机上不展示」的那一格哪儿都不出现,并在顶上说清有几格', () => {
const wrapper = mount(MobileFormReader, {
props: { schema: tabsSchema(), data: { reason: '出差', city: '北京', internal_no: 'N-9' } },
global
})
expect(wrapper.text()).toContain('有 1 格设了「手机上不展示」')
expect(wrapper.text()).not.toContain('N-9')
expect(wrapper.text()).not.toContain('内部流转号')
})
it('空着的一格留一行破折号,看得出这张单少填了什么', () => {
const wrapper = mount(MobileFormReader, {
props: { schema: tabsSchema(), data: { reason: '出差' } },
global
})
expect(visibleText(wrapper)).toContain('目的地—')
})
it('环节权限藏起来的格子不上屏', () => {
const wrapper = mount(MobileFormReader, {
props: { schema: tabsSchema(), data: { reason: '出差', city: '北京' }, perms: { city: 'hidden' } },
global
})
expect(visibleText(wrapper)).not.toContain('目的地')
})
it('附件摆缩略图、明细逐条只摆填了的列', () => {
const wrapper = mount(MobileFormReader, {
props: { schema: expenseSchema(), data: expenseData() },
global
})
expect(visibleText(wrapper)).toContain('2')
const table = wrapper.find('[data-test="m-reader-table"]')
expect(table.exists()).toBe(true)
expect(table.text()).toContain('第 1 条')
expect(table.text()).toContain('高铁上海→北京往返二等座')
// 第 2 条没写备注:那一列不占一行
expect(table.text()).not.toContain('第 2 条\n备注')
})
it('一张空表单也不炸', () => {
const wrapper = mount(MobileFormReader, { props: { schema: { fields: [] }, data: {} }, global })
expect(wrapper.find('[data-test="m-reader-empty"]').exists()).toBe(true)
})
})

View File

@ -0,0 +1,142 @@
<template>
<div class="space-y-2 pb-1">
<!-- 逐格开关要说得出在哪儿设:不然配表的人只看到单子少了几格,不知道是谁勾的 -->
<p v-if="plan.hidden" class="px-1 text-[11px] leading-relaxed text-gray-400 dark:text-dark-500" data-test="m-reader-hidden">
{{ t('mobile.fullSheetHidden', { count: plan.hidden }) }}
</p>
<p v-if="!plan.sections.length" class="py-3 text-sm text-gray-400" data-test="m-reader-empty">{{ t('start.formEmpty') }}</p>
<MobileFold
v-for="section in plan.sections"
:key="section.key"
:title="section.name"
:note="section.embed ? t('mobile.embedPage') : t('mobile.fieldCount', { count: section.rows.length })"
default-open
>
<!-- 外部系统那一页:手机上不内嵌别人的页面(390px 里嵌一整张 ERP 表等于没法看),
给一张卡片,点了在新窗口打开。 -->
<div v-if="section.embed" class="px-3.5 py-3">
<EmbedFrame
v-if="section.embedField"
:field="section.embedField"
:data="data"
:job="job"
:activity="activity"
:slot-key="slotKeyOf(section.embedField.key, section.key)"
readonly
printing
/>
<p v-else class="text-[13px] text-gray-400">{{ t('form.embedNotPicked') }}</p>
</div>
<div v-else class="divide-y divide-gray-100 dark:divide-dark-700">
<template v-for="row in section.rows" :key="row.field.key">
<!-- 附件与图片:缩略图直接摆出来,报销单最该看的就是这几张 -->
<div v-if="row.kind === 'media'" class="px-3.5 py-2.5" data-test="m-reader-media">
<p class="text-xs text-gray-400 dark:text-dark-500">
{{ row.field.label }} <span v-if="row.items.length" class="num ml-1 opacity-80">{{ row.items.length }}</span>
</p>
<AttachmentGallery v-if="row.items.length" :items="row.items" />
<p v-else class="mt-1 text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 明细:一格一行摊到底就是十几屏,逐条一段,每条只摆填了的那几列 -->
<div v-else-if="row.kind === 'table'" class="px-3.5 py-2.5" data-test="m-reader-table">
<p class="text-xs text-gray-400 dark:text-dark-500">
{{ row.field.label }}
<span class="num ml-1 opacity-80">{{ t('mobile.rowsCount', { count: row.rows.length }) }}</span>
</p>
<div
v-for="(item, index) in row.rows"
:key="index"
class="mt-2 rounded-lg bg-gray-50 px-2.5 py-2 dark:bg-dark-900/50"
>
<p class="num text-[11px] text-gray-400 dark:text-dark-500">{{ t('mobile.rowIndex', { index: index + 1 }) }}</p>
<p
v-for="cell in mobileRowCells(row.field, item)"
:key="cell.key"
class="mt-1 flex items-start justify-between gap-3"
>
<span class="flex-shrink-0 text-[13px] text-gray-400 dark:text-dark-500">{{ cell.label }}</span>
<span
class="min-w-0 flex-1 break-words text-right text-sm text-gray-900 dark:text-dark-100"
:class="cell.numeric ? 'num' : ''"
>{{ cell.value }}</span>
</p>
</div>
<p v-if="!row.rows.length" class="mt-1 text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 签名存的是那张图,摆图比摆「已签名」三个字有用 -->
<div v-else-if="row.kind === 'signature'" class="flex items-start justify-between gap-4 px-3.5 py-2.5">
<p class="flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">{{ row.field.label }}</p>
<img v-if="row.text" :src="row.text" :alt="t('mobile.signed')" class="max-h-16 max-w-[62%] object-contain" />
<p v-else class="text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 其余一格一行:左边问的是什么,右边是答案,空着也留一行,看得出这张单少填了什么 -->
<div
v-else
class="px-3.5 py-2.5"
:class="isLong(row) ? '' : 'flex items-start justify-between gap-4'"
data-test="m-reader-row"
>
<p class="text-xs text-gray-400 dark:text-dark-500">{{ row.field.label }}</p>
<p
class="break-words whitespace-pre-wrap text-[15px] leading-relaxed text-gray-900 dark:text-dark-100"
:class="[isLong(row) ? 'mt-1' : 'min-w-0 flex-1 text-right', row.field.type === 'money' || row.field.type === 'number' ? 'num' : '']"
>{{ row.text || EMPTY_MARK }}</p>
</div>
</template>
</div>
</MobileFold>
</div>
</template>
<script setup lang="ts">
/**
* 「完整单据」在手机上的那一屏:一格一行、按页签与分隔条分节、空值也留着。
*
* 这一屏以前直接塞桌面的 FormRenderer(readonly),代价有两处:
* 一是它那套分节位置按桌面 12 列网格的行号算,390px 上每格独占一行,行号全错配,
* 几段的段头会一起堆到最顶上;二是它把页签整个照搬过来,而手机上没人想在弹窗里
* 左右划页签。所以这一屏改成读 useFormPlan 那份计划——**同一套 tabPages 口径**,
* 只是换成手机上读得顺的摆法,一个字段都不少(除非设计器里勾了「手机上不展示」)。
*/
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import AttachmentGallery from '@/components/oa/AttachmentGallery.vue'
import EmbedFrame from '@/components/oa/EmbedFrame.vue'
import MobileFold from './MobileFold.vue'
import { mobileRowCells, readerSections } from './useFormPlan'
import { embedSlotKey } from '@/utils/tabPages'
import type { ReaderRow } from './useFormPlan'
import type { FormSchema } from '@/types'
const props = defineProps<{
schema: FormSchema | null
data: Record<string, unknown>
/** 环节字段权限,要用 expandPerms 展开过页签那一档;不给就全按能看见算 */
perms?: Record<string, string>
/** 下面这两样是外部页面那一格要用的:免登地址要后端按单据与环节现算 */
job?: string
activity?: string
}>()
const { t } = useI18n()
const EMPTY_MARK = '—'
const plan = computed(() => readerSections(props.schema, { data: props.data ?? {}, perms: props.perms ?? {} }))
/** 长文本自己占一块,别跟标签挤同一行 */
function isLong(row: ReaderRow): boolean {
return row.text.length > 44 || row.field.type === 'textarea' || row.field.type === 'richtext'
}
/** 外部页面那一格的回写分区键:宿主格子 key#页签 key(见 utils/tabPages.embedSlotKey) */
function slotKeyOf(hostKey: string, sectionKey: string): string {
return hostKey && sectionKey.startsWith('embed:') ? embedSlotKey(hostKey, sectionKey.slice('embed:'.length)) : ''
}
</script>

View File

@ -0,0 +1,264 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import type { FormFieldDef, MobileLayout } from '@/types'
import { planForm } from './useFormPlan'
import MobileFormSummary from './MobileFormSummary.vue'
import EmbedFrame from '@/components/oa/EmbedFrame.vue'
import type { FormPlan, PlanItem } from './useFormPlan'
/**
* 单据内容在手机上摊下来有多长:一节最多六行,剩下的按一下才出来。
* 归置口径本身由 useFormPlan.spec.ts 盯,这一份只管「摆了几行、怎么展开」。
*/
function item(n: number): PlanItem {
return {
field: { key: `f${n}`, label: `字段${n}`, type: 'input' } as unknown as FormFieldDef,
label: `字段${n}`,
text: `值${n}`,
long: false,
numeric: false,
kind: 'text',
style: 'row',
slotKey: '',
items: [],
rows: []
}
}
function plan(over: Partial<FormPlan> = {}): FormPlan {
return {
floats: [],
groups: [{ name: '基本信息', items: Array.from({ length: 12 }, (_, index) => item(index + 1)) }],
auto: [],
media: [],
table: {
field: { key: 'rows', label: '费用明细', type: 'table' } as unknown as FormFieldDef,
count: 12,
sum: '7,181.00'
},
signature: null,
hiddenMobile: 0,
dropped: 35,
total: 47,
custom: false,
showFull: true,
...over
}
}
/** MobileFold 收着用 v-show,看不见的行还在 DOM 里,按祖先的 display 过滤一次。 */
function rowsTexts(wrapper: ReturnType<typeof mount>): string[] {
return wrapper
.findAll('[data-test="m-row"]')
.filter((row) => {
let node: HTMLElement | null = row.element
while (node) {
if ((node.getAttribute('style') || '').includes('display: none')) return false
node = node.parentElement
}
return true
})
.map((row) => row.text().replace(/\s+/g, ' '))
}
function render(over: Partial<FormPlan> = {}) {
return mount(MobileFormSummary, {
props: { plan: plan(over) },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true, AttachmentGallery: true } }
})
}
describe('MobileFormSummary:一屏读不完的都得折起来', () => {
beforeEach(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
it('一节默认只摆六行,剩下的收成一颗「展开更早 6 条」', async () => {
const wrapper = render()
expect(rowsTexts(wrapper)).toHaveLength(6)
expect(rowsTexts(wrapper)[0]).toBe('字段1值1')
const more = wrapper.find('[data-test="m-group-more"]')
expect(more.text()).toBe('展开更早 6 条')
await more.trigger('click')
expect(rowsTexts(wrapper)).toHaveLength(12)
expect(wrapper.find('[data-test="m-group-more"]').exists()).toBe(false)
})
it('六行以内不给那颗钮,别为两行摆一颗多余的', () => {
const wrapper = render({
groups: [{ name: '基本信息', items: Array.from({ length: 6 }, (_, index) => item(index + 1)) }]
})
expect(rowsTexts(wrapper)).toHaveLength(6)
expect(wrapper.find('[data-test="m-group-more"]').exists()).toBe(false)
})
it('换一张单子,上一张摊开的状态不带过来', async () => {
const wrapper = render()
await wrapper.find('[data-test="m-group-more"]').trigger('click')
expect(rowsTexts(wrapper)).toHaveLength(12)
await wrapper.setProps({ plan: plan({ total: 48 }) })
expect(rowsTexts(wrapper)).toHaveLength(6)
})
it('明细只占一行(条数与合计都在那一行上),完整单据说清楚折了多少空值', () => {
const wrapper = render()
const table = wrapper.findAll('button').find((btn) => btn.text().includes('费用明细'))
expect(table?.text().replace(/\s+/g, ' ')).toBe('费用明细 · 12 条合计 7,181.00')
const full = wrapper.findAll('button').find((btn) => btn.text().includes('完整单据'))
expect(full?.text()).toContain('47 个字段,折了 35 个空的')
})
})
/**
* 按配置摆那一版:只出一节,摆法跟着格子走。
* 计划本身由 planForm 现算——这一份要盯的是"配成那样,屏幕上是不是那样"。
*/
describe('MobileFormSummary:配了手机端版式就只有一节', () => {
function fields(): FormFieldDef[] {
return [
{ key: 'sec', label: '一、基本信息', type: 'divider' },
{ key: 'reason', label: '报销事由', type: 'textarea' },
{ key: 'amount', label: '报销金额', type: 'money' },
{ key: 'starter', label: '发起人', type: 'auto' },
{ key: 'empty_note', label: '备注', type: 'text' },
{ key: 'rows', label: '费用明细', type: 'table', columns: [{ key: 'item', label: '事项', type: 'text' }, { key: 'money', label: '金额', type: 'money' }] },
{ key: 'invoices', label: '发票', type: 'attachment' }
] as unknown as FormFieldDef[]
}
const data = {
reason: '上海—北京客户巡访',
amount: 4860,
starter: '李明',
empty_note: '',
rows: [{ item: '高铁往返', money: 1129 }, { item: '住宿两晚', money: 1280 }],
invoices: [{ id: 'f1', name: '发票1.pdf', extension: 'pdf' }]
}
function renderMobile(mobile: MobileLayout, over: Record<string, unknown> = {}) {
const schema = { fields: fields(), layout: { columns: 12, grid: 12, mobile } } as unknown as Parameters<typeof planForm>[0]
const plan = planForm(schema, { data: { ...data, ...over } })
return mount(MobileFormSummary, {
props: { plan },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true, AttachmentGallery: true } }
})
}
const ORDER: MobileLayout = {
enabled: true,
title: '费用报销基本信息',
fields: [{ key: 'reason', style: 'block' }, { key: 'amount' }, { key: 'starter' }, { key: 'empty_note' }, { key: 'rows', style: 'card' }, { key: 'invoices' }]
}
it('只有一节,节名与顺序照配置;系统取数那一行不再出现', () => {
const wrapper = renderMobile(ORDER)
const sections = wrapper.findAll('[role="button"], .divide-y').length
expect(wrapper.text()).toContain('费用报销基本信息')
expect(wrapper.text()).not.toContain('系统取数')
expect(sections).toBeGreaterThan(0)
// 每格一行,左边那一段问的就是格子名;顺序必须与面板上从上到下一字不差
const labels = wrapper.findAll('[data-test="m-row"]').map((row) => row.findAll('p')[0].text())
expect(labels).toEqual(['报销事由', '报销金额', '发起人', '备注'])
})
it('十二格也不再折叠:点名要的格子不该被「展开更早 N 条」收起来', () => {
const many: MobileLayout = {
enabled: true,
title: '费用报销基本信息',
fields: Array.from({ length: 10 }, (_, index) => ({ key: `f${index}`, style: 'row' as const }))
}
const wide = fields().concat(Array.from({ length: 10 }, (_, index) => ({ key: `f${index}`, label: `字段${index}`, type: 'text' })) as unknown as FormFieldDef)
const schema = { fields: wide, layout: { columns: 12, grid: 12, mobile: many } } as unknown as Parameters<typeof planForm>[0]
const wrapper = mount(MobileFormSummary, {
props: { plan: planForm(schema, { data: {} }) },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true, AttachmentGallery: true } }
})
expect(wrapper.find('[data-test="m-group-more"]').exists()).toBe(false)
expect(wrapper.findAll('[data-test="m-row"]')).toHaveLength(10 + 4)
})
it('空着的那格留一个「—」,明细收成一行、点开走 openRows', async () => {
const wrapper = renderMobile(ORDER)
const note = wrapper.findAll('[data-test="m-row"]').find((row) => row.text().includes('备注'))
expect(note?.text().replace(/\s+/g, ' ')).toBe('备注—')
const table = wrapper.find('[data-test="m-custom-table"]')
expect(table.text()).toContain('费用明细')
await table.trigger('click')
expect(wrapper.emitted('openRows')).toHaveLength(1)
})
it('附件按缩略图摆在这一节里', () => {
const wrapper = renderMobile(ORDER)
expect(wrapper.find('[data-test="m-custom-media"]').exists()).toBe(true)
})
it('明细配成「逐条展开」就一条一段摊在这一节里', () => {
const wrapper = renderMobile({ ...ORDER, fields: ORDER.fields!.map((row) => (row.key === 'rows' ? { ...row, style: 'list' as const } : row)) })
const block = wrapper.find('[data-test="m-custom-table-list"]')
expect(block.text()).toContain('第 1 条')
expect(block.text()).toContain('高铁往返')
expect(wrapper.find('[data-test="m-custom-table"]').exists()).toBe(false)
})
it('「完整单据」入口配了才有', async () => {
const off = renderMobile(ORDER)
expect(off.text()).not.toContain('完整单据')
const on = renderMobile({ ...ORDER, showFullSheet: true })
const full = on.findAll('button').find((btn) => btn.text().includes('完整单据'))
expect(full).toBeTruthy()
await full?.trigger('click')
expect(on.emitted('openFull')).toHaveLength(1)
})
it('外部页面那一页摆一张「打开」卡片,卡片知道是哪一页、是哪张单', () => {
const withTabs = fields().concat([
{
key: 'tabs_host',
label: '标签页',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '费用报销基本信息' },
{ key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }
]
}
] as unknown as FormFieldDef[])
const layout: MobileLayout = { ...ORDER, fields: [...ORDER.fields!, { key: 'tabs_host#tab_2', style: 'embed' }] }
const schema = { fields: withTabs, layout: { columns: 12, grid: 12, mobile: layout } } as unknown as Parameters<typeof planForm>[0]
const wrapper = mount(MobileFormSummary, {
props: { plan: planForm(schema, { data }), data, job: 'j-9', activity: 'approve' },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true, AttachmentGallery: true, EmbedFrame: true } }
})
expect(wrapper.find('[data-test="m-custom-embed"]').exists()).toBe(true)
const frame = wrapper.findComponent(EmbedFrame)
// 免登地址要后端按"这张单 + 这一环 + 哪一页"现算,三样少一样都开不出对的那页
expect(frame.props('slotKey')).toBe('tabs_host#tab_2')
expect((frame.props('field') as FormFieldDef).label).toBe('费用报销发票信息')
expect(frame.props('job')).toBe('j-9')
expect(frame.props('activity')).toBe('approve')
// 手机上永远不内嵌别人的系统:只给卡片
expect(frame.props('printing')).toBe(true)
expect(frame.props('readonly')).toBe(true)
})
it('没配那一页时一个 EmbedFrame 都不渲染', () => {
const wrapper = renderMobile(ORDER)
expect(wrapper.find('[data-test="m-custom-embed"]').exists()).toBe(false)
expect(wrapper.findComponent(EmbedFrame).exists()).toBe(false)
})
it('没配这一档时还是从前那版:分节折叠 + 系统取数并一行 + 末尾完整单据', () => {
const schema = { fields: fields(), layout: { columns: 12, grid: 12 } } as unknown as Parameters<typeof planForm>[0]
const wrapper = mount(MobileFormSummary, {
props: { plan: planForm(schema, { data }) },
global: { plugins: [i18n], stubs: { teleport: true, Teleport: true, AttachmentGallery: true } }
})
// 同一张表、同一份数据,只是没开那一档:段名不再照配置,系统取数并成一行,入口照旧留着
expect(wrapper.text()).toContain('一、基本信息')
expect(wrapper.text()).toContain('系统取数')
expect(wrapper.text()).toContain('完整单据')
expect(wrapper.text()).not.toContain('费用报销基本信息')
})
})

View File

@ -0,0 +1,270 @@
<template>
<div class="space-y-2">
<!--
配了手机端版式(表单设计器 →「手机端」面板)就只出一节:这一节摆哪几格、按什么顺序、
每格怎么摆,全照那一份配置,不再自动并「系统取数」,末尾那颗「完整单据」也可有可无。
环节权限藏起来的格子照样不上屏——配置管的是"这张表想让人看什么",权限管的是"这一环能看什么"。
-->
<template v-if="plan.custom">
<MobileFold
v-for="group in plan.groups"
:key="group.name"
:title="group.name"
:note="t('mobile.fieldCount', { count: group.items.length })"
default-open
>
<div class="divide-y divide-gray-100 dark:divide-dark-700">
<!-- 两页外部页面共用宿主那一格的 key,所以按回写分区键当钥匙 -->
<template v-for="row in group.items" :key="row.slotKey || row.field.key">
<!-- 明细 · 收成一行:点了才逐条摊开(那一屏读 plan.table,与自动归置那版同一条路) -->
<button
v-if="row.kind === 'table' && row.style !== 'list'"
type="button"
class="flex w-full items-center gap-2 px-3.5 py-3 text-left"
data-test="m-custom-table"
@click="emit('openRows')"
>
<Icon name="table" class="h-[18px] w-[18px] flex-shrink-0 text-gray-400 dark:text-dark-500" />
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">{{ row.label }}</span>
<span class="num flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">{{ row.text }}</span>
<Icon name="chevronRight" class="h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
</button>
<!-- 明细 · 逐条展开:一条一段摊在这一节里,一段两行,扫的人先看花在什么上 -->
<div v-else-if="row.kind === 'table'" class="px-3.5 py-2.5" data-test="m-custom-table-list">
<p class="text-xs text-gray-400 dark:text-dark-500">
{{ row.label }} <span class="num ml-1 opacity-80">{{ row.text }}</span>
</p>
<div
v-for="(item, index) in row.rows"
:key="index"
class="mt-2 rounded-lg bg-gray-50 px-2.5 py-2 dark:bg-dark-900/50"
>
<p class="num text-[11px] text-gray-400 dark:text-dark-500">{{ t('mobile.rowIndex', { index: index + 1 }) }}</p>
<p v-for="cell in mobileRowCells(row.field, item)" :key="cell.key" class="mt-1 flex items-start justify-between gap-3">
<span class="flex-shrink-0 text-[13px] text-gray-400 dark:text-dark-500">{{ cell.label }}</span>
<span class="min-w-0 flex-1 break-words text-right text-sm text-gray-900 dark:text-dark-100" :class="cell.numeric ? 'num' : ''">
{{ cell.value }}
</span>
</p>
</div>
<p v-if="!row.rows.length" class="mt-1 text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 附件 · 缩略图:报销单最该看的就是这几张,收成一行「发票 2」等于藏起来 -->
<div v-else-if="row.kind === 'media' && row.style !== 'count'" class="px-3.5 py-2.5" data-test="m-custom-media">
<p class="text-xs text-gray-400 dark:text-dark-500">
{{ row.label }} <span v-if="row.items.length" class="num ml-1 opacity-80">{{ row.items.length }}</span>
</p>
<AttachmentGallery v-if="row.items.length" :items="row.items" />
<p v-else class="mt-1 text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 签名存的是那张图,摆图比摆「已签名」三个字有用 -->
<div v-else-if="row.kind === 'signature'" class="flex items-start justify-between gap-4 px-3.5 py-2.5">
<p class="flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">{{ row.label }}</p>
<img v-if="row.text" :src="row.text" :alt="t('mobile.signed')" class="max-h-16 max-w-[62%] object-contain" />
<p v-else class="text-[15px] text-gray-400 dark:text-dark-500">{{ EMPTY_MARK }}</p>
</div>
<!-- 外部页面那一页:手机上不内嵌别人的系统(390px 里嵌一整张 ERP 表等于没法看),
给一张「打开」卡片,点了新窗口看——与「完整单据」那一屏同一个口径。 -->
<div v-else-if="row.kind === 'embed'" class="px-3.5 py-2.5" data-test="m-custom-embed">
<EmbedFrame
:field="row.field"
:data="data"
:job="job"
:activity="activity"
:slot-key="row.slotKey"
readonly
printing
/>
</div>
<!-- 其余按配的那档摆:整段(标签在上)或一行(左问右答);空着也留一行,
配表的人点名要的格子不该因为没值就自己消失 -->
<div
v-else
class="px-3.5 py-2.5"
:class="row.style === 'block' || row.long ? '' : 'flex items-start justify-between gap-4'"
data-test="m-row"
>
<p class="text-xs text-gray-400 dark:text-dark-500">{{ row.label }}</p>
<p
class="break-words whitespace-pre-wrap text-[15px] leading-relaxed text-gray-900 dark:text-dark-100"
:class="[row.style === 'block' || row.long ? 'mt-1' : 'min-w-0 flex-1 text-right', row.numeric ? 'num' : '']"
>
{{ row.text || EMPTY_MARK }}
</p>
</div>
</template>
</div>
</MobileFold>
<button
v-if="plan.showFull"
type="button"
class="flex w-full items-center gap-2 rounded-xl bg-white px-3.5 py-3.5 text-left shadow-sm dark:bg-dark-800"
@click="emit('openFull')"
>
<Icon name="document" class="h-[18px] w-[18px] flex-shrink-0 text-gray-400 dark:text-dark-500" />
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">{{ t('mobile.viewFull') }}</span>
<span class="flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">
{{ t('mobile.fullHint', { total: plan.total, hidden: plan.dropped }) }}
</span>
<Icon name="chevronRight" class="h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
</button>
</template>
<template v-else>
<!-- 明细子表:手机上不做横向滚动表格,收成一行,点开看逐条 -->
<button
v-if="plan.table"
type="button"
class="flex w-full items-center gap-2 rounded-xl bg-white px-3.5 py-3.5 text-left shadow-sm dark:bg-dark-800"
@click="emit('openRows')"
>
<Icon name="table" class="h-[18px] w-[18px] flex-shrink-0 text-gray-400 dark:text-dark-500" />
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">
{{ plan.table.field.label }} · {{ t('mobile.rowsCount', { count: plan.table.count }) }}
</span>
<span v-if="plan.table.sum" class="num flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">
{{ t('mobile.rowsSum', { sum: plan.table.sum }) }}
</span>
<Icon name="chevronRight" class="h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
</button>
<MobileFold
v-for="(group, index) in plan.groups"
:key="group.name"
:title="group.name"
:note="t('mobile.fieldCount', { count: group.items.length })"
:default-open="index === 0"
>
<div class="divide-y divide-gray-100 dark:divide-dark-700">
<!-- 一节里最多摆这几行:47 格的单子摊开是六屏,而第一屏要的是「这单大概是什么」,
不是逐格读完。剩下的按一下才出来,逐格读还有「完整单据」那条路。
按配置摆那一版不走这一手——点名要的格子不该再被折叠藏起来。 -->
<div
v-for="row in shown(group)"
:key="row.field.key"
class="px-3.5 py-2.5"
:class="row.long ? '' : 'flex items-start justify-between gap-4'"
data-test="m-row"
>
<p class="text-xs text-gray-400 dark:text-dark-500">{{ row.label }}</p>
<p
class="break-words text-[15px] leading-relaxed text-gray-900 dark:text-dark-100"
:class="[row.long ? 'mt-1' : 'min-w-0 flex-1 text-right', row.numeric ? 'num' : '']"
>
{{ row.text }}
</p>
</div>
<button
v-if="group.items.length > GROUP_ROWS && !isOpen(group.name)"
type="button"
class="flex w-full items-center gap-1.5 px-3.5 py-2.5 text-left text-[13px] text-primary-600 dark:text-primary-400"
data-test="m-group-more"
@click="openGroup(group.name)"
>
<Icon name="chevronDown" class="h-4 w-4" />
{{ t('mobile.flowEarlier', { count: group.items.length - GROUP_ROWS }) }}
</button>
</div>
</MobileFold>
<!-- 系统取数那几格(发起人、工号、部门、上级…)合并成一行:抬头已经说过一次了 -->
<MobileFold
v-if="plan.auto.length"
icon="lock"
:title="t('mobile.autoFields')"
:note="t('mobile.fieldCount', { count: plan.auto.length })"
>
<div class="divide-y divide-gray-100 dark:divide-dark-700">
<div v-for="row in plan.auto" :key="row.field.key" class="flex items-start justify-between gap-4 px-3.5 py-2.5">
<p class="flex-shrink-0 text-[13px] text-gray-400 dark:text-dark-500">{{ row.label }}</p>
<p class="min-w-0 flex-1 break-words text-right text-sm text-gray-900 dark:text-dark-100">{{ row.text }}</p>
</div>
</div>
</MobileFold>
<!-- 附件与图片:发票、合同扫描件就住在表单那几格里。手机上只留一行「附件 3」,
等于把一单报销最该看的东西藏起来,所以缩略图直接摆出来,点开就是大图。 -->
<section
v-for="row in plan.media"
:key="row.field.key"
class="rounded-xl bg-white px-3.5 py-3 shadow-sm dark:bg-dark-800"
>
<p class="text-xs text-gray-400 dark:text-dark-500">
{{ row.field.label }} <span class="num ml-1 opacity-80">{{ row.items.length }}</span>
</p>
<AttachmentGallery :items="row.items" />
</section>
<button
type="button"
class="flex w-full items-center gap-2 rounded-xl bg-white px-3.5 py-3.5 text-left shadow-sm dark:bg-dark-800"
@click="emit('openFull')"
>
<Icon name="document" class="h-[18px] w-[18px] flex-shrink-0 text-gray-400 dark:text-dark-500" />
<span class="min-w-0 flex-1 truncate text-sm font-medium text-gray-900 dark:text-white">{{ t('mobile.viewFull') }}</span>
<span class="flex-shrink-0 text-xs text-gray-400 dark:text-dark-500">
{{ t('mobile.fullHint', { total: plan.total, hidden: plan.dropped }) }}
</span>
<Icon name="chevronRight" class="h-4 w-4 flex-shrink-0 text-gray-400 dark:text-dark-500" />
</button>
</template>
</div>
</template>
<script setup lang="ts">
/**
* 单据内容在手机上怎么排:两版走两条路。
*
* - **自动归置**(没配过的表单,也是原来那版):分节折叠 + 明细收成一行 + 系统取数合并成一行
* + 末尾一颗「完整单据」,判据全在 useFormPlan 里按字段类型算;
* - **按配置摆**(表单设计器「手机端」面板开了那一档):只出一节,节名、格子的顺序、
* 每格的摆法照 `layout.mobile` 那一份,值仍然由 useFormPlan 算成只读文本。
*
* 两版都不渲染控件——要改值的人在本环节的填写块里改,剩下的人本来就该看到只读的一份。
*/
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import AttachmentGallery from '@/components/oa/AttachmentGallery.vue'
import EmbedFrame from '@/components/oa/EmbedFrame.vue'
import MobileFold from './MobileFold.vue'
import { mobileRowCells } from './useFormPlan'
import type { FormPlan, PlanGroup, PlanItem } from './useFormPlan'
const props = defineProps<{
plan: FormPlan
/**
* 下面三样只有「外部页面」那一格用得上:免登地址要后端按这张单、这一环节现算。
* 没配那一格的表单一个都不传,也就一行代码都不会跑。
*/
data?: Record<string, unknown>
job?: string
activity?: string
}>()
const emit = defineEmits<{ openRows: []; openFull: [] }>()
const { t } = useI18n()
/** 空着的那一格写的记号:与「完整单据」那一屏同一个,两处读起来不该两种样子。 */
const EMPTY_MARK = '—'
/** 一节默认摆几行。六行是拇指一屏加半屏的量,再多就该折叠了。 */
const GROUP_ROWS = 6
const opened = ref<Set<string>>(new Set())
// 换一张单子(分节数会变)时把展开状态清回去,别让上一张的展开留在这一张上
watch(() => props.plan.total, () => (opened.value = new Set()))
function isOpen(name: string): boolean {
return opened.value.has(name)
}
function openGroup(name: string) {
opened.value = new Set(opened.value).add(name)
}
function shown(group: PlanGroup): PlanItem[] {
return isOpen(group.name) ? group.items : group.items.slice(0, GROUP_ROWS)
}
</script>

View File

@ -0,0 +1,193 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { nextTick } from 'vue'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import { useAppStore } from '@/stores/app'
import { useAuthStore } from '@/stores/auth'
import type { User } from '@/types'
import { APP_BUILD } from '@/utils/appBuild'
import MobileHome from './MobileHome.vue'
const api = vi.hoisted(() => ({
workbench: vi.fn(),
listReadCompleted: vi.fn(),
countProcessing: vi.fn(),
countRead: vi.fn(),
listNotifications: vi.fn(async () => ({ items: [] })),
unreadCount: vi.fn(async () => ({ count: 0 }))
}))
vi.mock('@/api', () => ({
supportAPI: { workbench: api.workbench },
workAPI: { listReadCompleted: api.listReadCompleted }
}))
// 待办、待阅那两个角标计数住在 appStore 里,取数用的是各自的 api 模块,不是 @/api 这层壳
vi.mock('@/api/task', () => ({ countProcessing: api.countProcessing }))
vi.mock('@/api/work', () => ({ countRead: api.countRead }))
// 铃铛那个未读数走的是 appStore,appStore 用的是 @/api/support,这层也得桩住
vi.mock('@/api/support', () => ({
listNotifications: api.listNotifications,
unreadCount: api.unreadCount
}))
const ALL = ['work:workbench', 'work:todo', 'work:done', 'work:read', 'work:created', 'work:start', 'work:profile']
const SEED = {
todo: 12,
expired: 2,
done: 34,
read: 3,
readDone: 56,
created: 8
}
const ZERO = { todo: 0, expired: 0, done: 0, read: 0, readDone: 0, created: 0 }
/** 卡片里那几个 span 之间夹着换行和缩进,比文本前先归一次空白。 */
function flat(text: string): string {
return text.replace(/\s+/g, ' ').trim()
}
async function render(options: { seed?: typeof SEED; permissions?: string[] } = {}) {
const pinia = createPinia()
setActivePinia(pinia)
useAuthStore().$patch({
user: {
id: 'u1',
account: 'boss',
display_name: '周总',
permissions: options.permissions ?? ALL,
organization_name: '经营管理部'
} as unknown as User,
token: 'token'
} as never)
const r = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/workbench', component: { template: '<div />' } },
{ path: '/todo', component: { template: '<div />' } },
{ path: '/done', component: { template: '<div />' } },
{ path: '/read', component: { template: '<div />' } },
{ path: '/created', component: { template: '<div />' } },
{ path: '/start', component: { template: '<div />' } }
]
})
await r.push('/workbench')
await r.isReady()
const wrapper = mount(MobileHome, {
props: options.seed ? { seed: options.seed } : {},
// 通知那层是 bottom sheet(Teleport 到 body),桩掉才留在 wrapper 里
global: { plugins: [r, pinia, i18n], stubs: { teleport: true, Teleport: true } }
})
await flushPromises()
return { wrapper, appStore: useAppStore() }
}
// 卡片里图标、名字、数字、超时那枚各自一个 span,中间没有空白,拼起来就是这一串
const FIVE = ['待办12已超时 2', '已办34', '待阅3', '已阅56', '我发起的8']
const cardTexts = (wrapper: Awaited<ReturnType<typeof render>>['wrapper']) =>
wrapper.findAll('[data-test="m-home-card"]').map((card) => flat(card.text()))
beforeEach(() => {
api.workbench.mockReset().mockResolvedValue({ completed: 34, created_total: 8, expired: 2 })
api.listReadCompleted.mockReset().mockResolvedValue({
items: [],
total: 56,
page: 1,
page_size: 1,
pages: 0
})
api.countProcessing.mockReset().mockResolvedValue({ total: 12, expired: 2 })
api.countRead.mockReset().mockResolvedValue({ total: 3, need: 1 })
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
describe('手机端首页那五张卡片', () => {
it('五张卡片按待办、已办、待阅、已阅、我发起的排,各带自己的条数', async () => {
const { wrapper } = await render({ seed: SEED })
expect(cardTexts(wrapper)).toEqual(FIVE)
})
it('一张卡对应一张列表,已阅那张直接递 ?tab=done 过去', async () => {
const { wrapper } = await render({ seed: ZERO })
expect(wrapper.findAll('[data-test="m-home-card"]').map((card) => card.attributes('href'))).toEqual([
'/todo',
'/done',
'/read',
'/read?tab=done',
'/created'
])
})
it('没权限的那张不摆:已办、我发起的都按自己那条权限走', async () => {
// 已阅与待阅是同一张列表的两个档位,共用 work:read,不单独卡一道权限
const { wrapper } = await render({
seed: SEED,
permissions: ['work:workbench', 'work:todo', 'work:read']
})
expect(cardTexts(wrapper)).toEqual(['待办12已超时 2', '待阅3', '已阅56'])
})
it('发起流程从底部栏挪到首页,还跟着 work:start 走', async () => {
const withStart = await render({ seed: ZERO })
const start = withStart.wrapper.find('[data-test="m-start"]')
expect(flat(start.text())).toBe('发起流程')
expect(start.attributes('href')).toBe('/start')
const withoutStart = await render({
seed: ZERO,
permissions: ALL.filter((code) => code !== 'work:start')
})
expect(withoutStart.wrapper.find('[data-test="m-start"]').exists()).toBe(false)
})
it('数从各自那张列表的口径来:角标计数、工作台统计、已阅列表的 total', async () => {
const { wrapper, appStore } = await render()
expect(appStore.todoCount).toBe(12)
expect(appStore.readCount).toBe(3)
expect(api.workbench).toHaveBeenCalledTimes(1)
expect(api.listReadCompleted).toHaveBeenCalledWith({
page: 1,
page_size: 1
})
expect(cardTexts(wrapper)).toEqual(FIVE)
})
it('首屏摆着构建号:手机上这一串对得上镜像 tag,就说明新版式真的发上去了', async () => {
const { wrapper } = await render({ seed: ZERO })
expect(wrapper.find('[data-test="m-build"]').text()).toBe(APP_BUILD)
})
it('铃铛挂在抬头:未读点看一眼就知道,列表在底部弹层里读', async () => {
const { wrapper, appStore } = await render({ seed: ZERO })
const bell = wrapper.find('[data-test="m-bell"]')
// 抬头那一排只有图标,名字挂在 aria-label 上(读屏与悬浮提示都读它)
expect(bell.attributes('aria-label')).toBe('通知消息')
expect(wrapper.find('[data-test="m-bell-dot"]').exists()).toBe(false)
appStore.notificationUnread = 3
await nextTick()
expect(wrapper.find('[data-test="m-bell-dot"]').exists()).toBe(true)
await bell.trigger('click')
await flushPromises()
expect(api.listNotifications).toHaveBeenCalled()
const sheet = wrapper.find('[data-test="m-notice"]')
expect(sheet.exists()).toBe(true)
expect(sheet.text()).toContain('都读过了')
expect(sheet.text()).toContain('暂无通知')
})
it('统计接口挂了不弹红条:数字归零,五张卡片还在', async () => {
api.workbench.mockRejectedValue(new Error('boom'))
api.listReadCompleted.mockRejectedValue(new Error('boom'))
const { wrapper, appStore } = await render()
expect(cardTexts(wrapper)).toEqual(['待办12', '已办0', '待阅3', '已阅0', '我发起的0'])
expect(appStore.toasts).toHaveLength(0)
})
})

View File

@ -0,0 +1,278 @@
<template>
<div>
<!-- 顶上一档贴住屏幕两边(-mx-4 抵掉 AppLayout 那个 main 的 p-4),下面再自己收回 16px。
问候只留两行:手机上第一屏该留给那五张卡片,不该留给一句问候语的排版。 -->
<header
class="-mx-4 flex items-start gap-2 border-b border-gray-100 bg-white/95 px-4 pb-3.5 pt-4 backdrop-blur dark:border-dark-700 dark:bg-dark-800/95"
>
<div class="min-w-0 flex-1">
<h2 class="truncate text-[17px] font-semibold text-gray-900 dark:text-white">
{{
t('workbench.greeting', {
name: authStore.user?.display_name ?? ''
})
}}
</h2>
<p class="mt-1 truncate text-xs text-gray-400 dark:text-dark-500">
{{ subtitle }}
<!-- 构建号就是镜像 tag:手机上扫一眼这一串,对得上集群里那个 Pod,就说明新版式真的发上去了 -->
<span class="num ml-1 text-[10px] text-gray-400 dark:text-dark-500" data-test="m-build">{{ APP_BUILD }}</span>
</p>
</div>
<!-- 桌面上铃铛在顶栏,手机上顶栏整条没了,未读就挂在这颗钮上 -->
<button
type="button"
class="relative flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
:aria-label="t('workbench.notifications')"
data-test="m-bell"
@click="openNotice"
>
<Icon name="bell" class="h-[18px] w-[18px] text-gray-500 dark:text-dark-400" />
<span
v-if="appStore.notificationUnread"
class="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-red-500"
data-test="m-bell-dot"
></span>
</button>
<button
type="button"
class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
:aria-label="t('common.refresh')"
data-test="m-refresh"
@click="load"
>
<Icon
name="refresh"
class="h-[18px] w-[18px] text-gray-500 dark:text-dark-400"
:class="busy ? 'animate-spin' : ''"
/>
</button>
</header>
<!-- 五张卡片就是手机上的一级导航:待办、已办、待阅、已阅、我发起的。
桌面上那套侧边栏 + 统计卡 + 概览在 390px 上要先滚两屏才够得着,这里把它们折成
伸手就到的五个方块,一张卡片一个列表,数字就是那个列表点进去的条数。 -->
<div class="grid grid-cols-2 gap-2.5 px-4 pt-3">
<RouterLink
v-for="card in cards"
:key="card.key"
:to="card.to"
class="flex overflow-hidden rounded-xl bg-white p-3.5 shadow-sm transition active:scale-[0.996] dark:bg-dark-800"
:class="card.wide ? 'col-span-2 flex-row items-center gap-3' : 'flex-col'"
data-test="m-home-card"
>
<span class="flex min-w-0 items-center gap-2" :class="card.wide ? 'flex-1' : ''">
<span class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg" :class="card.tint">
<Icon :name="card.icon" class="h-4 w-4" />
</span>
<span class="min-w-0 flex-1 truncate text-[13px] font-medium text-gray-500 dark:text-dark-400">{{
card.label
}}</span>
</span>
<!-- 最后一张占满整行,横着摆才不空:名字在左,数字顶到右边 -->
<span class="flex items-end gap-1.5" :class="card.wide ? 'flex-shrink-0' : 'mt-3'">
<!-- 数还没回来先占住这一块高度,免得数字一到整屏往下跳 -->
<span v-if="card.value === null" class="h-6 w-8 animate-pulse rounded bg-gray-200 dark:bg-dark-700"></span>
<span
v-else
class="num text-[24px] font-semibold leading-none"
:class="
card.urgent && card.value ? 'text-primary-600 dark:text-primary-400' : 'text-gray-900 dark:text-white'
"
>{{ card.value > 99 ? '99+' : card.value }}</span
>
<span v-if="card.hint" class="badge badge-danger mb-0.5">{{ card.hint }}</span>
</span>
</RouterLink>
</div>
<!-- 发起流程从底部标签栏挪到这儿:底部那一条只剩首页 / 待办 / 我的,
领导用得多的是批单子,发起是偶尔一次,不值得常驻一格。 -->
<div v-if="canStart" class="px-4 pt-4">
<RouterLink
to="/start"
class="btn btn-secondary flex w-full items-center justify-center py-2.5"
data-test="m-start"
>
<Icon name="plus" class="mr-1 h-4 w-4" />
{{ t('nav.startProcess') }}
</RouterLink>
</div>
<MobileNotificationSheet :show="noticeOpen" @close="noticeOpen = false" />
</div>
</template>
<script setup lang="ts">
/**
* 手机端首页:五张小卡片,一张一个列表。
*
* 数字的出处都跟点进去那张列表同源,不自己另算一套:
* 待办、待阅 appStore 里那两个角标计数(AppLayout 统一取,侧边栏和底部栏用的也是它们)
* 已办、我发起的 工作台统计接口里的 completed / created_total(后端注释里写明与这两张列表同口径)
* 已阅 已阅列表的 total,只取一页一条,只要那个数
* 所以卡片上写 8,点进去就是 8 条;不会出现「这里 8 那里 12」。
*/
import { computed, onMounted, ref } from 'vue'
import { RouterLink } from 'vue-router'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import MobileNotificationSheet from './MobileNotificationSheet.vue'
import { supportAPI, workAPI } from '@/api'
import { useAuthStore } from '@/stores/auth'
import { useAppStore } from '@/stores/app'
import { APP_BUILD } from '@/utils/appBuild'
/** 预览台与测试给的那份现成数字:给了就不打接口。 */
export interface MobileHomeCounts {
todo: number
expired: number
done: number
read: number
readDone: number
created: number
}
type IconName = InstanceType<typeof Icon>['$props']['name']
interface HomeCard {
key: string
label: string
icon: IconName
tint: string
to: string | { path: string; query: Record<string, string> }
value: number | null
/** 等着办的才染成品牌色,看过的数字没必要喊人 */
urgent?: boolean
hint?: string
wide?: boolean
}
const props = defineProps<{ seed?: MobileHomeCounts | null }>()
const { t } = useI18n()
const appStore = useAppStore()
const authStore = useAuthStore()
const busy = ref(false)
const noticeOpen = ref(false)
/** 统计接口那三个数;null = 还没回来。 */
const counts = ref<{
done: number
created: number
readDone: number
expired: number
} | null>(null)
const today = computed(() =>
new Date().toLocaleDateString('zh-CN', {
month: 'long',
day: 'numeric',
weekday: 'long'
})
)
const subtitle = computed(() => {
const org = authStore.user?.organization_path || authStore.user?.organization_name || ''
return org ? `${today.value} · ${org}` : today.value
})
const canStart = computed(() => authStore.can('work:start'))
const CARD_PERMISSIONS: Record<string, string> = {
todo: 'work:todo',
done: 'work:done',
read: 'work:read',
'read-done': 'work:read',
created: 'work:created'
}
const cards = computed<HomeCard[]>(() => {
const seed = props.seed
const stats = counts.value
return (
(
[
{
key: 'todo',
label: t('mobile.cardTodo'),
icon: 'inbox',
tint: 'bg-primary-100 text-primary-600 dark:bg-primary-900/30 dark:text-primary-400',
to: '/todo',
value: seed ? seed.todo : appStore.todoCount,
urgent: true,
hint: (seed?.expired ?? stats?.expired) ? `${t('task.expired')} ${seed?.expired ?? stats?.expired}` : ''
},
{
key: 'done',
label: t('mobile.cardDone'),
icon: 'checkCircle',
tint: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400',
to: '/done',
value: seed ? seed.done : (stats?.done ?? null)
},
{
key: 'read',
label: t('mobile.cardRead'),
icon: 'mail',
tint: 'bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400',
to: '/read',
value: seed ? seed.read : appStore.readCount,
urgent: true
},
{
key: 'read-done',
label: t('mobile.cardReadDone'),
icon: 'eye',
tint: 'bg-gray-100 text-gray-500 dark:bg-dark-700 dark:text-dark-400',
to: { path: '/read', query: { tab: 'done' } },
value: seed ? seed.readDone : (stats?.readDone ?? null)
},
{
key: 'created',
label: t('mobile.cardCreated'),
icon: 'paperAirplane',
tint: 'bg-indigo-100 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400',
to: '/created',
value: seed ? seed.created : (stats?.created ?? null),
wide: true
}
] as HomeCard[]
)
// 权限判据与侧边栏、底部标签栏同一套:没这个入口的人不会在这儿看见一张点不进去的卡片
.filter((card) => authStore.can(CARD_PERMISSIONS[card.key]))
)
})
async function load() {
busy.value = true
try {
// 三路一起问:少一趟来回就是少一次白屏。任一路失败都不弹错误条——首页少个数字
// 不致命,弹三条红条反而像系统坏了。
const [stats, readDonePage] = await Promise.all([
supportAPI.workbench().catch(() => null),
workAPI.listReadCompleted({ page: 1, page_size: 1 }).catch(() => null),
// 铃铛那个小红点跟着这一次刷新一起取,不为一个数单开一趟
appStore.loadNotifications()
])
counts.value = {
done: Number(stats?.completed ?? 0),
created: Number(stats?.created_total ?? 0),
readDone: Number(readDonePage?.total ?? 0),
expired: Number(stats?.expired ?? 0)
}
await appStore.refreshBadgeCounts()
} finally {
busy.value = false
}
}
async function openNotice() {
noticeOpen.value = true
// 点开铃铛就是要看新的,直接读一次;失败就算了,弹层里会说"暂无通知"
await appStore.loadNotifications()
}
onMounted(() => {
if (!props.seed) load()
})
</script>

View File

@ -0,0 +1,71 @@
<template>
<!-- 手机上没有顶栏那颗铃铛的下拉,通知就落在这张底部弹层里读。 -->
<MobileSheet :show="show" test="m-notice" :title="t('workbench.notifications')" @close="emit('close')">
<div class="pb-1">
<div class="mb-2 flex items-center gap-2">
<p class="min-w-0 flex-1 text-[13px] text-gray-400 dark:text-dark-500">
{{ unread ? t('mobile.noticeUnread', { count: unread }) : t('mobile.noticeAllRead') }}
</p>
<button
v-if="unread"
type="button"
class="flex-shrink-0 text-[13px] text-primary-600 dark:text-primary-400"
data-test="m-notice-read-all"
@click="appStore.markNotificationsRead()"
>
{{ t('mobile.markAllRead') }}
</button>
</div>
<button
v-for="item in appStore.notifications"
:key="item.id"
type="button"
class="mb-1.5 w-full rounded-xl px-3.5 py-3 text-left transition active:bg-gray-50 dark:active:bg-dark-700"
:class="item.read ? 'bg-gray-50/70 dark:bg-dark-700/50' : 'bg-white shadow-sm dark:bg-dark-800'"
data-test="m-notice-item"
@click="open(item)"
>
<p class="flex items-start gap-2">
<span class="min-w-0 flex-1 text-[14px] font-medium leading-snug text-gray-900 dark:text-white">{{ item.title }}</span>
<span v-if="!item.read" class="mt-1 h-1.5 w-1.5 flex-shrink-0 rounded-full bg-red-500"></span>
</p>
<p class="mt-1 line-clamp-2 text-[13px] leading-relaxed text-gray-500 dark:text-dark-400">{{ item.body }}</p>
<p class="mt-1 text-[11px] text-gray-400 dark:text-dark-500">{{ item.create_time }}</p>
</button>
<p v-if="!appStore.notifications.length" class="py-8 text-center text-[13px] text-gray-400 dark:text-dark-500">
{{ t('workbench.noNotification') }}
</p>
</div>
</MobileSheet>
</template>
<script setup lang="ts">
/**
* 手机上读通知的那一层。
*
* 列表与未读数住在 appStore 里:桌面上顶栏那份下拉读的是同一份,两处不会各数一个未读。
* 点开一条就顺手标已读,再按 task / job 把单子端到人面前——通知只是入口,
* 值得单独一屏的东西不该只有这一条列表,所以不做单独的通知页。
*/
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import MobileSheet from './MobileSheet.vue'
import { useAppStore } from '@/stores/app'
import type { NotificationItem } from '@/types'
defineProps<{ show: boolean }>()
const emit = defineEmits<{ close: [] }>()
const { t } = useI18n()
const router = useRouter()
const appStore = useAppStore()
const unread = computed(() => appStore.notificationUnread)
async function open(item: NotificationItem) {
await appStore.readNotification(item)
emit('close')
if (item.task) await router.push(`/todo/${item.task}`)
else if (item.job) await router.push(`/work/${item.job}`)
}
</script>

View File

@ -0,0 +1,35 @@
<template>
<!-- 下拉刷新那一句:压在顶栏正中那一小块,不占文档流——往下挪就盖住关键数字那一行了。
手势期间标题被这枚胶囊挡一下是各家 App 的通用做法,松手即散。 -->
<div
v-if="state !== 'hidden'"
class="pointer-events-none fixed inset-x-0 top-2 z-30 flex justify-center"
data-test="m-pull"
aria-live="polite"
>
<span
class="flex items-center gap-1.5 rounded-full bg-white/95 px-3 py-1.5 text-[12px] text-gray-500 shadow-md backdrop-blur dark:bg-dark-800/95 dark:text-dark-300"
>
<Icon name="refresh" class="h-3.5 w-3.5" :class="state === 'loading' ? 'animate-spin' : ''" />
{{ label }}
</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import type { PullState } from '@/composables/useMobileRefresh'
const props = defineProps<{ state: PullState }>()
const { t } = useI18n()
const label = computed(() =>
props.state === 'loading'
? t('mobile.pullLoading')
: props.state === 'ready'
? t('mobile.pullReady')
: t('mobile.pullMore')
)
</script>

View File

@ -0,0 +1,60 @@
<template>
<Teleport to="body">
<Transition name="m-sheet">
<div v-if="show" class="fixed inset-0 z-40">
<div class="absolute inset-0 bg-black/45" data-test="sheet-mask" @click="emit('close')"></div>
<div
class="absolute inset-x-0 bottom-0 flex flex-col rounded-t-2xl bg-white pb-[env(safe-area-inset-bottom)] shadow-2xl dark:bg-dark-900"
:class="full ? 'top-9' : 'max-h-[88%]'"
:data-test="test"
role="dialog"
:aria-label="title"
>
<div class="mx-auto mt-2 h-1 w-9 flex-shrink-0 rounded-full bg-gray-200 dark:bg-dark-700"></div>
<div class="flex-shrink-0 px-4 pb-2 pt-3">
<p class="text-base font-semibold text-gray-900 dark:text-white">{{ title }}</p>
<p v-if="desc" class="mt-1 text-xs leading-relaxed text-gray-400 dark:text-dark-500">{{ desc }}</p>
</div>
<div class="min-h-0 flex-1 overflow-y-auto px-4"><slot /></div>
<div
v-if="$slots.footer"
class="flex flex-shrink-0 gap-2 border-t border-gray-100 px-4 pb-3 pt-3 dark:border-dark-700"
>
<slot name="footer" />
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
/**
* 手机上唯一的浮层容器:一律从屏幕下沿推上来,拇指够得着,也躲开了企微自带的顶部标题栏。
*
* 桌面端的弹窗(BaseDialog)居中显示、宽度按内容撑,那套尺寸在 375px 上会把「确定」
* 顶到屏幕外。审批动作的弹层都只需要「填一点东西 + 一颗主按钮」,做成 bottom sheet
* 之后主按钮永远在同一个位置,闭着眼睛都点得到。
*/
/**
* `full`:给「完整单据」「明细逐条」那种要读到底的内容,直接顶到屏幕上沿,
* 不然底下那条操作位会一直压着最后两行。
*/
withDefaults(defineProps<{ show: boolean; title: string; desc?: string; full?: boolean; test?: string }>(), { desc: '', full: false, test: '' })
const emit = defineEmits<{ close: [] }>()
</script>
<style scoped>
.m-sheet-enter-active .absolute.inset-x-0,
.m-sheet-leave-active .absolute.inset-x-0 {
transition: transform 0.26s cubic-bezier(0.32, 0.72, 0.24, 1);
}
.m-sheet-enter-from .absolute.inset-x-0,
.m-sheet-leave-to .absolute.inset-x-0 {
transform: translateY(101%);
}
.m-sheet-enter-from .bg-black\/45,
.m-sheet-leave-to .bg-black\/45 {
opacity: 0;
}
</style>

View File

@ -0,0 +1,213 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import ExternalCheckPanel from '@/components/oa/ExternalCheckPanel.vue'
import MobileTaskView from './MobileTaskView.vue'
import { TASK_VIEW_KEY } from './taskContext'
import { expenseDetail, stubView } from './mobileFixtures'
const api = vi.hoisted(() => ({ listProcessing: vi.fn(), getTask: vi.fn() }))
vi.mock('@/api', () => ({
taskAPI: { listProcessing: api.listProcessing, execute: vi.fn(), goBackTargets: api.getTask },
workAPI: { share: vi.fn() }
}))
function router() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/todo', name: 'my-todo', component: { template: '<div />' } },
{ path: '/todo/:id', name: 'todo-detail', component: { template: '<div />' } }
]
})
}
async function render(view = stubView(expenseDetail())) {
const r = router()
await r.push('/todo/task-1')
await r.isReady()
const wrapper = mount(MobileTaskView, {
global: {
plugins: [r, createPinia(), i18n],
provide: { [TASK_VIEW_KEY as symbol]: view },
stubs: {
teleport: true,
// 这几块各自要数据源、要接口、要剪贴板,是各自的测试该管的事;
// 这里只看手机版式把什么摆在哪儿。
FormRenderer: true,
ExternalCheckPanel: true,
AttachmentGallery: true,
OpinionComposer: true,
PeoplePicker: true
}
}
})
await flushPromises()
return { wrapper, view }
}
/** 从屏底那颗「同意」走到意见弹层:两条出口这一档要先挑一条。 */
async function approveFlow(wrapper: Awaited<ReturnType<typeof render>>['wrapper']) {
await wrapper.find('[data-test="m-agree"]').trigger('click')
const routes = wrapper.find('[data-test="m-routes"]').findAll('[data-test="m-route"]')
await routes[0]!.trigger('click')
await flushPromises()
}
beforeEach(() => {
setActivePinia(createPinia())
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
api.listProcessing.mockReset().mockResolvedValue({ items: [], total: 0, page: 1, page_size: 2, pages: 0 })
})
describe('手机上的审批页', () => {
it('抬头先答四问:这一单是什么、谁提的、多少钱、卡在哪', async () => {
const { wrapper } = await render()
const text = wrapper.text()
expect(text).toContain('差旅报销 · 上海—北京客户巡访')
expect(text).toContain('李明')
expect(text).toContain('总经理审批')
expect(text).toContain('4,860.00 元')
// 核准金额这一格是本环节要填的,它归填写块,不在摘要里重复出现
expect(text).not.toContain('4,800.00 元')
})
it('空着的那格不在屏上占一行,作废的内部编号这一环被藏了也不露', async () => {
const { wrapper } = await render()
expect(wrapper.text()).not.toContain('已作废的内部编号')
expect(wrapper.text()).not.toMatch(/备注\s*$/)
})
it('要人填的格子交给填写块,读的那一份不重复摆', async () => {
const { view } = await render()
const schema = view.formSchema.value!
const editable = ['approved', 'days']
expect(schema.fields.filter((field) => editable.includes(field.key)).length).toBe(2)
})
it('必填没填时不给点同意,先把缺的那几句说出来', async () => {
const { wrapper } = await render(stubView(expenseDetail(), { requiredMissing: ['出差天数'] }))
expect(wrapper.text()).toContain('先填这几项:出差天数')
expect(wrapper.find('[data-test="m-agree"]').exists()).toBe(false)
})
it('这一环有两条出口时,先选一条,再写意见', async () => {
const { wrapper, view } = await render()
await wrapper.find('[data-test="m-agree"]').trigger('click')
const routes = wrapper.find('[data-test="m-routes"]').findAll('[data-test="m-route"]')
expect(routes).toHaveLength(2)
// 每条出口都写着它去哪儿:点了才知道单子跑到哪个环节,是手机上最不该有的事
expect(routes[0]!.text()).toContain('财务复核')
expect(routes[1]!.text()).toContain('提交')
await routes[1]!.trigger('click')
await flushPromises()
expect(view.calls.map((call) => call.name)).toContain('pickRoute')
expect(wrapper.find('[data-test="m-approve"]').exists()).toBe(true)
expect(wrapper.find('[data-test="m-routes"]').exists()).toBe(false)
})
it('一句话意见点一下就填进意见框', async () => {
const { wrapper, view } = await render()
await approveFlow(wrapper)
const chips = wrapper.find('[data-test="m-approve"]').findAll('[data-test="m-phrase"]')
expect(chips.length).toBeGreaterThan(2)
await chips.find((chip) => chip.text() === '拟同意')!.trigger('click')
expect(view.opinion.value).toBe('拟同意')
})
it('提交这一步整个交给桌面那份逻辑,手机上不多算一遍', async () => {
api.listProcessing.mockResolvedValue({ items: [], total: 0, page: 1, page_size: 2, pages: 0 })
const { wrapper, view } = await render()
await approveFlow(wrapper)
await wrapper.find('[data-test="m-submit"]').trigger('click')
await flushPromises()
expect(view.calls.map((call) => call.name)).toContain('submit')
// 手上一条不剩,就回待办列表,不把人留在一张办完的单子上
expect(view.calls.filter((call) => call.name === 'submit')).toHaveLength(1)
})
it('退回带得上目标与方式,加签抄送分享都从更多里够得着', async () => {
const { wrapper, view } = await render()
await wrapper.find('[data-test="m-goback"]').trigger('click')
expect(view.calls.map((call) => call.name)).toContain('openGoBack')
// 退回不是点开就算完:目标环节、退法、意见三样都得在这一层里给齐
const back = wrapper.find('[data-test="m-goback-sheet"]')
expect(back.text()).toContain('上一环节')
expect(back.text()).toContain('逐级退回')
await wrapper.find('[data-test="m-more"]').trigger('click')
const menu = wrapper.find('[data-test="m-menu"]')
expect(menu.text()).toContain('加签')
expect(menu.text()).toContain('转办')
expect(menu.text()).toContain('抄送')
expect(menu.text()).toContain('分享')
// 打印在手机上没有出口:手机上没有打印机,真要出纸是回电脑上的详情页做的事
expect(menu.text()).not.toContain('打印')
await menu.findAll('button').find((btn) => btn.text().includes('抄送'))!.trigger('click')
expect(view.calls.map((call) => call.name)).toContain('openSend')
// 抄送那一层要多问一句「要不要对方也办」,这一档桌面上有,手机上不能少
const people = wrapper.find('[data-test="m-people"]')
expect(people.text()).toContain('抄送无需处理')
expect(people.text()).toContain('抄送需处理')
expect(people.text()).toContain('选择人员')
})
it('此刻走不了的出口当场说为什么,点它也不会被带走', async () => {
const view = stubView(expenseDetail(), { blocked: ['退回修改'] })
const { wrapper } = await render(view)
await wrapper.find('[data-test="m-agree"]').trigger('click')
const sheet = wrapper.find('[data-test="m-routes"]')
// 屏头的说明先报数:两条出口、其中一条此刻走不了
expect(sheet.text()).toContain('这一环配了 2 条出口')
expect(sheet.text()).toContain('其中 1 条当前走不了')
const blocked = sheet.findAll('[data-test="m-route"]')[1]!
expect(blocked.text()).toContain('适用条件不成立,走不了')
expect(blocked.attributes('aria-disabled')).toBe('true')
await blocked.trigger('click')
await flushPromises()
// 真被挡下了:没选中任何出口,意见那一屏也不该出现
expect(view.routeName.value).toBe('')
expect(wrapper.find('[data-test="m-approve"]').exists()).toBe(false)
})
it('摘要之外还有一条退路:完整单据里一个字段都不会少', async () => {
const { wrapper } = await render()
await wrapper.findAll('button').find((btn) => btn.text().includes('完整单据'))!.trigger('click')
const reader = wrapper.find('[data-test="m-reader"]')
expect(reader.exists()).toBe(true)
// 被折叠掉的那些(系统取数、空值)在这一份里都在
expect(reader.text()).toContain('只读')
})
it('不归他办的那一张:操作位上不说谎,只说这条已经办过了', async () => {
const view = stubView(expenseDetail({ can_process: false }))
const { wrapper } = await render(view)
expect(wrapper.find('[data-test="m-agree"]').exists()).toBe(false)
expect(wrapper.text()).toContain('该待办已被处理')
})
it('外部核验面板照常挂在单据页签里,只是不改判据', async () => {
const { wrapper } = await render()
wrapper.unmount()
const r = router()
await r.push('/todo/task-1')
await r.isReady()
const full = mount(MobileTaskView, {
global: {
plugins: [r, createPinia(), i18n],
provide: { [TASK_VIEW_KEY as symbol]: stubView(expenseDetail()) },
stubs: { teleport: true, FormRenderer: true, AttachmentGallery: true, OpinionComposer: true, PeoplePicker: true }
}
})
await flushPromises()
expect(full.findComponent(ExternalCheckPanel).exists()).toBe(true)
})
})

View File

@ -0,0 +1,747 @@
<template>
<div class="min-h-full pb-[calc(4.75rem+env(safe-area-inset-bottom))]">
<div v-if="loading" class="space-y-2 px-3.5 pt-3" aria-hidden="true">
<div v-for="i in 3" :key="i" class="animate-pulse rounded-xl bg-white p-4 shadow-sm dark:bg-dark-800">
<div class="h-3 w-1/3 rounded bg-gray-200 dark:bg-dark-700"></div>
<div class="mt-3 h-4 w-4/5 rounded bg-gray-200 dark:bg-dark-700"></div>
<div class="mt-3 h-3 w-2/3 rounded bg-gray-100 dark:bg-dark-600"></div>
</div>
</div>
<template v-else-if="detail && task">
<!-- 顶栏:这一档不挂 AppHeader(见 router 上那句 chromeless),返回得由自己给。
标题只摆单据标题。流程名称、单号·提交时间、那一串描述在手机上没人读:
单号落在「进度」那一栏最底下,什么时候谁提的本来就是这条流转的第一步。
刷新那颗按钮也撤了——它离拇指最远,而刷新这件事手机上有一把手势专门干(往下拉)。 -->
<div class="sticky top-0 z-20 flex h-11 items-center gap-1 bg-white/95 px-1.5 backdrop-blur dark:bg-dark-800/95">
<button type="button" class="flex h-9 w-9 items-center justify-center rounded-lg" :aria-label="t('common.back')" @click="backToList">
<Icon name="arrowLeft" class="h-5 w-5 text-gray-700 dark:text-dark-200" />
</button>
<p class="min-w-0 flex-1 truncate text-[15px] font-semibold text-gray-900 dark:text-white">
{{ detail.title || detail.process_name }}
</p>
</div>
<MobilePullPill :state="pullState" />
<!-- 抬头就一行:左边是这张单此刻卡在哪,右端是谁提的;金额那一档是关键数字,留着。
以前这五排(流程名 / 单号·时间 / 标题 / 标题会改成什么 / 发起人)划下去要占小半屏,
而批单子的人要答的就「卡在哪、谁提的、多少钱」这三样。 -->
<div class="bg-white px-4 pb-3 pt-2 dark:bg-dark-800">
<div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">
<span :class="badgeClass(workStatusVariant(detail.status))">{{ workStatusLabel(detail.status) }}</span>
<span class="badge badge-primary">{{ task.activity_name }}</span>
<span v-if="task.expired" class="badge badge-danger">{{ t('task.expired') }}</span>
<span v-else-if="task.expire_time" class="badge badge-warning">{{ formatDateTimeToMinute(task.expire_time) }}</span>
<span v-if="task.press_count" class="badge badge-warning">{{ t('task.press') }} {{ task.press_count }}</span>
<span v-if="ctx.handleLocked.value" class="badge badge-purple">{{ t('task.oaLockedTag') }}</span>
<span class="ml-auto flex min-w-0 items-center gap-1.5 text-[13px] text-gray-500 dark:text-dark-400">
<span class="flex h-[18px] w-[18px] flex-shrink-0 items-center justify-center rounded-full bg-primary-100 text-[10px] font-medium text-primary-700 dark:bg-primary-900/60 dark:text-primary-300">
{{ (detail.creator_person || '').slice(0, 1) }}
</span>
<span class="min-w-0 truncate">{{ detail.creator_person || personText(task.identity) }}</span>
<span v-if="detail.creator_unit_name" class="hidden truncate sm:inline">· {{ detail.creator_unit_name }}</span>
</span>
</div>
<div v-if="plan.floats.length" class="mt-2.5 flex gap-7 overflow-x-auto border-t border-gray-100 pt-2.5 dark:border-dark-700">
<div v-for="row in plan.floats" :key="row.field.key" class="flex-shrink-0">
<p class="text-[11px] text-gray-400 dark:text-dark-500">{{ row.field.label }}</p>
<p class="num mt-0.5 whitespace-nowrap text-[19px] font-bold leading-tight text-gray-900 dark:text-white">{{ row.text }}</p>
</div>
</div>
</div>
<!-- 此刻办不动的原因:写回卡住、整条挂起、按钮外锁、不归他办,各说一句就好 -->
<div class="space-y-2 px-3.5 pt-2">
<p v-if="ctx.writebackBlocked.value" class="flex items-start gap-2 rounded-xl bg-red-50 px-3 py-2.5 text-[13px] leading-relaxed text-red-700 dark:bg-red-900/25 dark:text-red-200">
<Icon name="lock" class="mt-0.5 h-4 w-4 flex-shrink-0" />{{ ctx.writebackNote.value }}
</p>
<p v-else-if="ctx.frozen.value" class="flex items-start gap-2 rounded-xl bg-amber-50 px-3 py-2.5 text-[13px] text-amber-800 dark:bg-amber-900/25 dark:text-amber-200">
<Icon name="pause" class="mt-0.5 h-4 w-4 flex-shrink-0" />{{ t('task.suspended') }}
<span v-if="detail.pause_reason" class="min-w-0 flex-1">{{ detail.pause_reason }}</span>
</p>
<p v-else-if="!canProcess" class="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2.5 text-[13px] text-amber-800 dark:bg-amber-900/25 dark:text-amber-200">
<Icon name="infoCircle" class="h-4 w-4 flex-shrink-0" />{{ t('task.taskHandled') }}
</p>
<p v-if="ctx.handleLocked.value" class="flex items-start gap-2 rounded-xl bg-indigo-50 px-3 py-2.5 text-[13px] leading-relaxed text-indigo-900 dark:bg-indigo-900/25 dark:text-indigo-100">
<Icon name="lock" class="mt-0.5 h-4 w-4 flex-shrink-0" />{{ ctx.oaLockText.value }}
</p>
<p v-else-if="task.empower_from_identity" class="flex items-center gap-2 rounded-xl bg-primary-50 px-3 py-2.5 text-[13px] text-primary-800 dark:bg-primary-900/25 dark:text-primary-100">
<Icon name="swap" class="h-4 w-4 flex-shrink-0" />{{ t('task.empoweredTo', { name: personText(task.empower_from_identity) }) }}
</p>
<div
v-for="item in ctx.nodeDecisions.value"
:key="item.id"
class="rounded-xl border border-primary-200 bg-primary-50 px-3.5 py-3 text-[13px] text-primary-900 dark:border-primary-500/30 dark:bg-primary-900/20 dark:text-primary-100"
>
<p class="font-medium leading-relaxed">{{ t('task.nodeDecisionBanner', { app: item.appName || item.app, action: item.kindLabel, route: item.route }) }}</p>
<div class="mt-2 flex gap-2">
<button type="button" class="btn btn-primary btn-sm flex-1" @click="ctx.confirmDecision(item.id, next)">{{ t('task.nodeDecisionConfirm') }}</button>
<button type="button" class="btn btn-secondary btn-sm" @click="ctx.rejectDecision(item.id)">{{ t('task.nodeDecisionReject') }}</button>
</div>
</div>
</div>
<!-- 两页签就够:单据内容、审批进度。桌面上那张流程图画布在 375px 上缩成一团,
进度时间线本来就把「走到哪了、在等谁」说完了,手机上不再留画布。 -->
<div class="sticky top-11 z-20 mt-2 flex gap-5 border-b border-gray-100 bg-white px-4 dark:border-dark-700 dark:bg-dark-800">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
class="relative py-2.5 text-sm"
:class="tabKey === tab.key ? 'font-semibold text-gray-900 dark:text-white' : 'text-gray-400 dark:text-dark-500'"
@click="tabKey = tab.key"
>
{{ tab.label }}
<span v-if="tab.count" class="num ml-0.5 text-[11px] opacity-70">{{ tab.count }}</span>
<span v-if="tabKey === tab.key" class="absolute inset-x-0 -bottom-px h-0.5 rounded bg-primary-600"></span>
</button>
</div>
<div class="space-y-2 px-3.5 py-3">
<template v-if="tabKey === 'form'">
<!-- 本环节要填的那几格:手机上提到最前面,读单子的路上顺手就填了,
不必像桌面那样去右栏找。意见不在这里——那是按下「同意」之后的事。 -->
<div v-if="canProcess && !ctx.frozen.value && needFields.length" class="rounded-xl border border-primary-200 bg-white px-3.5 py-3 dark:border-primary-500/30 dark:bg-dark-800">
<p class="flex flex-wrap items-center gap-1.5 text-[13px] font-semibold text-primary-700 dark:text-primary-300">
<Icon name="edit" class="h-4 w-4" />{{ t('mobile.needFill') }}
<span class="font-normal opacity-75">{{ t('mobile.needFillHint', { count: needFields.length }) }}</span>
</p>
<p v-if="ctx.requiredMissing.value.length" class="mt-1.5 text-xs text-red-500">
{{ t('start.fillFirst') }}:{{ ctx.requiredMissing.value.join('、') }}
</p>
<div ref="fillEl" class="mt-2">
<FormRenderer
:schema="needSchema"
:model-value="ctx.formData.value"
:perms="ctx.fieldPerms.value"
:job="detail.job"
:process="detail.process"
:process-name="detail.process_name"
:activity="task.activity"
:activity-name="task.activity_name"
:at-start="ctx.atBegin.value"
@update:model-value="ctx.formData.value = $event"
/>
</div>
</div>
<MobileFormSummary
:plan="plan"
:data="ctx.formData.value"
:job="detail.job"
:activity="task.activity"
@open-rows="rowsOpen = true"
@open-full="fullOpen = true"
/>
<MobileFold
v-if="detail.attachments.length"
icon="paperclip"
:title="t('task.attachments')"
:note="String(detail.attachments.length)"
>
<div class="px-3.5 py-3"><AttachmentGallery :items="detail.attachments" /></div>
</MobileFold>
<!-- 外部核验:点同意之前先看清这一单在对方系统里是什么下场 -->
<div class="empty:hidden">
<ExternalCheckPanel :job="detail.job" :readonly="!canProcess || ctx.frozen.value" @changed="ctx.reload()" />
</div>
</template>
<div v-else class="rounded-xl bg-white px-3.5 py-3 shadow-sm dark:bg-dark-800">
<MobileFlow
:ref="bindRecordPanel"
:items="detail.task_completed"
:routes="detail.routes"
:pending="detail.tasks"
:start="ctx.startRecord.value"
:comments="ctx.comments.value"
:logs="detail.work_logs"
:my-identity="ctx.myIdentity.value"
:can-comment="ctx.canComment.value"
:busy="ctx.busy.value"
:draft-key="`comment:${detail.id}`"
:serial="detail.serial || ''"
@comment="ctx.confirmComment($event)"
@remove="ctx.removeComment($event)"
/>
</div>
</div>
<!-- 吸底操作栏:这一档底下没有标签栏(chromeless),所以它独占屏幕下沿,
「同意」永远在同一个位置,拇指不用找。 -->
<div class="fixed inset-x-0 bottom-0 z-20 flex items-center gap-2 border-t border-gray-100 bg-white/95 px-3.5 pb-[calc(0.625rem+env(safe-area-inset-bottom))] pt-2.5 backdrop-blur dark:border-dark-700 dark:bg-dark-800/95">
<template v-if="canProcess && !ctx.frozen.value">
<p v-if="ctx.requiredMissing.value.length" class="min-w-0 flex-1 truncate text-xs text-amber-600 dark:text-amber-400">
{{ t('mobile.fillBeforeApprove', { fields: ctx.requiredMissing.value.join('、') }) }}
</p>
<template v-else>
<button type="button" class="btn btn-primary flex-1" :disabled="ctx.busy.value" data-test="m-agree" @click="startApprove">
<Icon name="check" class="mr-1 h-4 w-4" />{{ t('task.rapidAgree') }}
</button>
<button
v-if="node?.allow_go_back"
type="button"
class="btn btn-secondary flex-none px-4"
:disabled="ctx.busy.value || ctx.goBackLocked.value"
:title="ctx.goBackLocked.value ? ctx.oaLockText.value : ''"
data-test="m-goback"
@click="ctx.openGoBack()"
>
{{ t('task.goback') }}
</button>
</template>
</template>
<button v-else type="button" class="btn btn-secondary flex-1" disabled>
{{ ctx.frozen.value ? t('task.suspended') : canProcess ? t('task.oaLockedTag') : t('task.taskHandled') }}
</button>
<button type="button" class="btn btn-secondary flex-none px-3" :aria-label="t('common.more')" data-test="m-more" @click="menuOpen = true">
<Icon name="more" class="h-5 w-5" />
</button>
</div>
<!-- 多出口:先选走哪条,再写意见。去向写在按钮上,不用点了才知道 -->
<MobileSheet :show="routeSheet" test="m-routes" :title="t('mobile.pickRoute')" :desc="routeSheetDesc" @close="routeSheet = false">
<div class="pb-1">
<button
v-for="item in routeButtons"
:key="item.name"
type="button"
class="mb-2 flex w-full items-center gap-2 rounded-xl border px-3.5 py-3.5 text-left"
:class="item.ok ? 'border-gray-200 dark:border-dark-600' : 'border-gray-100 opacity-60 dark:border-dark-700'"
:aria-disabled="!item.ok"
:title="item.ok ? '' : t('task.routeConditionUnmet')"
data-test="m-route"
@click="pickAndApprove(item)"
>
<span class="min-w-0 flex-1">
<span class="block text-[15px] font-semibold text-gray-900 dark:text-white">{{ item.name }}</span>
<!-- 走不了的那几条当场说为什么:手机上没有悬停,等人点完再吃一句提示是白费一次拇指 -->
<span class="mt-0.5 block text-xs" :class="item.ok ? 'text-gray-400 dark:text-dark-500' : 'text-amber-600 dark:text-amber-400'">
{{ item.ok ? item.target || t('mobile.routeByCondition') : t('mobile.routeBlocked') }}
</span>
</span>
<Icon :name="item.ok ? 'chevronRight' : 'infoCircle'" class="h-4 w-4 flex-shrink-0 text-gray-400" />
</button>
</div>
</MobileSheet>
<!-- 同意:一屏里只有「说一句 + 提交」。要填的格子在单据页签里,这里不再摆一遍 -->
<MobileSheet :show="approveSheet" test="m-approve" :title="`${t('task.rapidAgree')} · ${task.activity_name}`" :desc="approveDesc" @close="approveSheet = false">
<div class="pb-1">
<div v-if="needFields.length" class="mb-3 flex items-center gap-2 rounded-lg bg-gray-50 px-3 py-2 text-[13px] text-gray-600 dark:bg-dark-700 dark:text-dark-300">
<Icon name="checkCircle" class="h-4 w-4 flex-shrink-0 text-green-600" />
{{ t('mobile.needFill') }}
<span class="num">{{ filledCount }}/{{ needFields.length }}</span>
<button type="button" class="ml-auto flex-shrink-0 text-primary-600 dark:text-primary-400" @click="backToFill">{{ t('mobile.change') }}</button>
</div>
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('task.opinion') }}</p>
<div class="mb-2 flex flex-wrap gap-1.5">
<button
v-for="phrase in phrases"
:key="phrase"
type="button"
class="rounded-full border border-gray-200 px-3 py-1.5 text-[13px] text-gray-600 active:bg-gray-50 dark:border-dark-600 dark:text-dark-300 dark:active:bg-dark-700"
data-test="m-phrase"
@click="ctx.opinion.value = phrase"
>
{{ phrase }}
</button>
</div>
<OpinionComposer
:ref="bindOpinionEditor"
:model-value="ctx.opinion.value"
purpose="opinion"
:placeholder="t('task.opinionPlaceholder')"
:busy="ctx.busy.value"
:draft-key="`op:${task.id}`"
:min-height="76"
@update:model-value="ctx.opinion.value = $event"
/>
</div>
<template #footer>
<button type="button" class="btn btn-secondary flex-none px-5" @click="approveSheet = false">{{ t('mobile.lookAgain') }}</button>
<button type="button" class="btn btn-primary flex-1" :disabled="ctx.busy.value" data-test="m-submit" @click="approve">
{{ ctx.busy.value ? t('common.loading') : t('mobile.submitNext') }}
</button>
</template>
</MobileSheet>
<!-- 退回:目标、方式、意见。与桌面那一个弹窗同样的三样,一样不少 -->
<MobileSheet :show="ctx.goBackShow.value" test="m-goback-sheet" :title="t('task.goback')" :desc="t('mobile.goBackHint')" @close="ctx.goBackShow.value = false">
<div class="pb-1">
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('task.gobackTarget') }}</p>
<button
v-for="item in ctx.goBackOptions.value"
:key="item.value"
type="button"
class="mb-2 flex w-full items-center gap-2.5 rounded-xl border px-3.5 py-3 text-left"
:class="ctx.goBackActivity.value === item.value ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20' : 'border-gray-200 dark:border-dark-600'"
@click="ctx.goBackActivity.value = item.value"
>
<span class="h-4 w-4 flex-shrink-0 rounded-full border" :class="ctx.goBackActivity.value === item.value ? 'border-[5px] border-primary-600' : 'border-2 border-gray-300 dark:border-dark-500'"></span>
<span class="text-[15px] text-gray-900 dark:text-white">{{ item.label }}</span>
</button>
<p class="mb-1.5 mt-3 text-xs text-gray-400 dark:text-dark-500">{{ t('task.gobackWay') }}</p>
<div class="flex gap-2">
<button
v-for="opt in ctx.goBackWayOptions.value"
:key="opt.value"
type="button"
class="flex-1 rounded-lg border py-2 text-[13px]"
:class="ctx.goBackWay.value === opt.value ? 'border-primary-500 bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300' : 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'"
@click="ctx.goBackWay.value = opt.value"
>
{{ opt.label }}
</button>
</div>
<p class="mb-1.5 mt-3 text-xs text-gray-400 dark:text-dark-500">{{ t('task.opinion') }}</p>
<TextArea v-model="ctx.goBackOpinion.value" :rows="3" :placeholder="t('task.opinionPlaceholder')" />
</div>
<template #footer>
<button type="button" class="btn btn-secondary flex-none px-5" @click="ctx.goBackShow.value = false">{{ t('common.cancel') }}</button>
<button type="button" class="btn btn-danger flex-1" :disabled="ctx.busy.value" @click="ctx.confirmGoBack(next)">{{ t('common.confirm') }}</button>
</template>
</MobileSheet>
<!-- 加签 / 转办 / 抄送 / 分享:四件事共用一个面板,选项与桌面弹窗一一对上 -->
<MobileSheet :show="ctx.peopleShow.value || ctx.sendShow.value" test="m-people" :title="peopleTitle" :desc="peopleDesc" @close="closePeople">
<div class="pb-1">
<div v-if="ctx.sendShow.value && ctx.sendMode.value === 'cc'" class="mb-3">
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('process.ccAction') }}</p>
<div class="flex gap-2">
<button
type="button"
class="flex-1 rounded-lg border py-2 text-[13px]"
:class="!ctx.sendRequiresAction.value ? 'border-primary-500 bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300' : 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'"
@click="ctx.sendRequiresAction.value = false"
>
{{ t('task.ccNone') }}
</button>
<button
type="button"
class="flex-1 rounded-lg border py-2 text-[13px]"
:class="ctx.sendRequiresAction.value ? 'border-primary-500 bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300' : 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'"
@click="ctx.sendRequiresAction.value = true"
>
{{ t('task.ccNeed') }}
</button>
</div>
<p class="input-hint">{{ ctx.sendRequiresAction.value ? t('process.ccActionHint') : t('process.ccActionNoneHint') }}</p>
</div>
<div v-if="ctx.peopleShow.value && ctx.peopleMode.value === 'add'" class="mb-3 flex gap-2">
<div class="flex-1">
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('task.addTaskWay') }}</p>
<div class="flex gap-2">
<button
v-for="opt in [{ v: 'before', l: t('task.addTaskBefore') }, { v: 'after', l: t('task.addTaskAfter') }]"
:key="opt.v"
type="button"
class="flex-1 rounded-lg border py-2 text-[13px]"
:class="ctx.addWay.value === opt.v ? 'border-primary-500 bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300' : 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'"
@click="ctx.addWay.value = opt.v as 'before' | 'after'"
>
{{ opt.l }}
</button>
</div>
</div>
<div class="flex-1">
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('task.addTaskMode') }}</p>
<div class="flex gap-2">
<button
v-for="opt in [{ v: 'together', l: t('task.addTaskTogether') }, { v: 'serial', l: t('task.addTaskSerial') }]"
:key="opt.v"
type="button"
class="flex-1 rounded-lg border py-2 text-[13px]"
:class="ctx.addMode.value === opt.v ? 'border-primary-500 bg-primary-50 text-primary-700 dark:bg-primary-900/20 dark:text-primary-300' : 'border-gray-200 text-gray-600 dark:border-dark-600 dark:text-dark-300'"
@click="ctx.addMode.value = opt.v as 'together' | 'serial'"
>
{{ opt.l }}
</button>
</div>
</div>
</div>
<p class="mb-1.5 text-xs text-gray-400 dark:text-dark-500">{{ t('task.selectPeople') }} <span class="text-red-500">*</span></p>
<PeoplePicker :model-value="peopleModel" @update:model-value="setPeople" />
<p class="mb-1.5 mt-3 text-xs text-gray-400 dark:text-dark-500">{{ t('task.opinion') }}</p>
<TextArea :model-value="peopleOpinionModel" :rows="2" @update:model-value="setPeopleOpinion" />
</div>
<template #footer>
<button type="button" class="btn btn-secondary flex-none px-5" @click="closePeople">{{ t('common.cancel') }}</button>
<button v-if="ctx.sendShow.value" type="button" class="btn btn-primary flex-1" :disabled="ctx.busy.value" @click="send">{{ t('common.confirm') }}</button>
<button v-else type="button" class="btn btn-primary flex-1" :disabled="ctx.busy.value" @click="ctx.confirmPeople(ctx.peopleMode.value === 'transfer' ? next : undefined)">{{ t('common.confirm') }}</button>
</template>
</MobileSheet>
<!-- 更多:换人、抄送、分享、完整单据,加上「电脑版」和字号这两条退路(打印不给,见 menuItems) -->
<MobileSheet :show="menuOpen" test="m-menu" :title="t('task.moreActions')" @close="menuOpen = false">
<div class="pb-1">
<button
v-for="item in menuItems"
:key="item.key"
type="button"
class="flex w-full items-center gap-2.5 rounded-xl px-2 py-3 text-left text-[15px] text-gray-800 dark:text-dark-100"
@click="runMenu(item.key)"
>
<Icon :name="item.icon" class="h-[18px] w-[18px] text-gray-400 dark:text-dark-400" />{{ item.label }}
</button>
<div class="mt-2 flex items-center gap-2 rounded-xl bg-gray-50 px-3 py-2.5 dark:bg-dark-700">
<Icon name="edit" class="h-4 w-4 flex-shrink-0 text-gray-400" />
<span class="flex-1 text-[13px] text-gray-500 dark:text-dark-400">{{ t('mobile.fontScale') }}</span>
<div class="flex gap-1">
<button
v-for="opt in fontOptions"
:key="opt.value"
type="button"
class="rounded-lg border px-2.5 py-1"
:class="fontScale === opt.value ? 'border-primary-500 bg-white text-primary-700 dark:bg-dark-800' : 'border-gray-200 text-gray-500 dark:border-dark-600'"
@click="setFontScale(opt.value)"
>
{{ opt.label }}
</button>
</div>
</div>
</div>
</MobileSheet>
<!-- 完整单据:摘要看不到了才展开,用的是桌面那套只读渲染,一个字段都不会少 -->
<MobileSheet :show="fullOpen || rowsOpen" test="m-reader" :title="fullOpen ? t('mobile.viewFull') : plan.table?.field.label || ''" :desc="fullOpen ? fullDesc : ''" full @close="closeReader">
<div class="pb-1">
<!-- 手机上这一屏用自己的读法:按页签和分隔条分节,一格一行,空着也留一行。
桌面那套只读渲染的分节位置是按 12 列网格的行号算的,搬到 390px 上会全错配。 -->
<MobileFormReader
v-if="fullOpen"
:schema="formSchema"
:data="ctx.formData.value"
:perms="expandedPerms"
:job="detail.job"
:activity="task.activity"
/>
<!-- 一条两行:第一行「第几条 · 花在什么上 · 多少钱」,第二行日子与备注。
十二行明细摊成四行一条就是两屏半,扫完得划半天。 -->
<div v-else-if="plan.table" class="space-y-2">
<div v-for="(row, index) in tableRows" :key="index" class="rounded-xl bg-white px-3.5 py-3 dark:bg-dark-800">
<p class="flex items-baseline gap-2">
<span class="num text-xs text-gray-400 dark:text-dark-500">{{ t('mobile.rowIndex', { index: index + 1 }) }}</span>
<span class="min-w-0 flex-1 truncate text-[15px] font-medium text-gray-900 dark:text-white">{{ rowHead(row) }}</span>
<span v-if="rowMoney(row)" class="num flex-shrink-0 text-[15px] font-semibold text-gray-900 dark:text-white">{{ rowMoney(row) }}</span>
</p>
<p v-if="rowTail(row)" class="mt-1.5 text-xs text-gray-400 dark:text-dark-500">{{ rowTail(row) }}</p>
</div>
</div>
</div>
</MobileSheet>
</template>
<EmptyState v-else icon="inbox" :title="t('task.taskHandled')" :description="t('common.noData')">
<template #action>
<button type="button" class="btn btn-secondary" @click="backToList">{{ t('common.back') }}</button>
</template>
</EmptyState>
</div>
</template>
<script setup lang="ts">
/**
* 手机上的审批页:一屏读完该读的,底下那颗「同意」把单批掉,办完直接跳下一条。
*
* 这里没有第二套审批逻辑。出口怎么合、哪几格这一环能改、必填那道闸、退回能退到哪几环、
* 写回卡没卡、OA 按钮锁没锁、表单里那几格附件要不要随行交上去——全部来自 TaskDetailView
* 交出的那一份(taskContext.ts)。手机版式只做两件事:把它摆成竖屏的样子,以及决定
* 「办完去哪儿」。所以桌面每补一处判据,这一页自动跟着,不会有「电脑上能批、手机上批不动」。
*
* 与桌面版的分工还有一层:桌面上那些列筛选、批量审批、流程图画布是为一次处理几十条单子
* 准备的,手机上领导一次就批几条,那些控件加起来比单子本身还占地方,于是都不进来。
*/
import { computed, inject, nextTick, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import TextArea from '@/components/common/TextArea.vue'
import FormRenderer from '@/components/oa/FormRenderer.vue'
import AttachmentGallery from '@/components/oa/AttachmentGallery.vue'
import MobileFlow from './MobileFlow.vue'
import OpinionComposer from '@/components/oa/OpinionComposer.vue'
import PeoplePicker from '@/components/oa/PeoplePicker.vue'
import ExternalCheckPanel from '@/components/oa/ExternalCheckPanel.vue'
import MobileSheet from './MobileSheet.vue'
import MobileFold from './MobileFold.vue'
import MobileFormReader from './MobileFormReader.vue'
import MobileFormSummary from './MobileFormSummary.vue'
import MobilePullPill from './MobilePullPill.vue'
import { TASK_VIEW_KEY, type TaskRouteButton, type TaskView } from './taskContext'
import { planForm, fieldText } from './useFormPlan'
import type { FormFieldDef } from '@/types'
import { useMobileShell, type FontScale } from '@/composables/useMobileShell'
import { usePullToRefresh } from '@/composables/useMobileRefresh'
import { expandPerms } from '@/utils/tabPages'
import { personText } from '@/utils/personLabel'
import { taskAPI } from '@/api'
import { useAppStore } from '@/stores/app'
import { badgeClass, workStatusLabel, workStatusVariant } from '@/utils/oa'
import { formatDateTimeToMinute } from '@/utils/format'
type IconName = InstanceType<typeof Icon>['$props']['name']
type TabKey = 'form' | 'progress'
const { t, tm } = useI18n()
const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const { fontScale, setFontScale, pinDesktop } = useMobileShell()
const ctx = inject(TASK_VIEW_KEY) as TaskView
// 下拉刷新:这一屏有正在填的填写块,所以只在人主动下拉时取,回到前台不自动刷——
// 那是拿人家写了一半的字去换一次「也许更新了」。
const { state: pullState } = usePullToRefresh(() => ctx.reload())
const loading = computed(() => ctx.loading.value)
const detail = computed(() => ctx.detail.value)
const task = computed(() => ctx.task.value)
const canProcess = computed(() => ctx.canProcess.value)
const node = computed(() => ctx.node.value)
const formSchema = computed(() => ctx.formSchema.value)
const routeButtons = computed(() => ctx.routeButtons.value)
const tabKey = ref<TabKey>('form')
const routeSheet = ref(false)
const approveSheet = ref(false)
const menuOpen = ref(false)
const fullOpen = ref(false)
const rowsOpen = ref(false)
const taskId = computed(() => String(route.params.id ?? ''))
/**
* 一句话意见:词条存的是数组,取原始那一份。
* 用 t() 取不行——它会把串里的 | 当复数分隔符,五十条意见只剩第一条。
*/
// tm 的推导类型在这份词条上绕不出来(TS2589),取原始消息这件事本来就只想要一个数组,
// 先把口子收窄再问,比给词条加类型注记便宜。
const rawMessage = tm as unknown as (key: string) => unknown
const phrases = computed<string[]>(() => {
const raw = rawMessage('mobile.phrases')
return Array.isArray(raw) ? raw.map(String) : []
})
const fontOptions = computed<{ value: FontScale; label: string }[]>(() => [
{ value: 'm', label: t('mobile.fontM') },
{ value: 'l', label: t('mobile.fontL') },
{ value: 'xl', label: t('mobile.fontXL') }
])
const tabs = computed(() => [
{ key: 'form' as TabKey, label: t('work.formData'), count: 0 },
{ key: 'progress' as TabKey, label: t('task.approvalHistory'), count: detail.value?.task_completed.length ?? 0 }
])
/** 环节权限先按页签展开一遍:「藏整片 / 藏某一页」记在页签那一档,逐格看不出这一层 */
const expandedPerms = computed(() => expandPerms(formSchema.value?.fields ?? [], ctx.fieldPerms.value))
/** 这一环能改的那几格:桌面摆在右栏处理面板里,手机上提到单据最前面。 */
const needFields = computed(() => {
const fields = formSchema.value?.fields ?? []
return fields.filter((field) => ['editable', 'required'].includes(String(expandedPerms.value[field.key] ?? '')))
})
const needSchema = computed(() => ({ ...(formSchema.value ?? { fields: [] }), fields: needFields.value, layout: { ...(formSchema.value?.layout ?? {}), columns: 1 } }))
const filledCount = computed(() => needFields.value.length - ctx.requiredMissing.value.length)
const plan = computed(() =>
planForm(formSchema.value, {
data: ctx.formData.value,
perms: expandedPerms.value,
needKeys: needFields.value.map((field) => field.key)
})
)
const tableRows = computed<Record<string, unknown>[]>(() => {
const field = plan.value.table?.field
const value = field ? ctx.formData.value[field.key] : null
return Array.isArray(value) ? (value as Record<string, unknown>[]) : []
})
const visibleCols = computed(() => (plan.value.table?.field.columns ?? []).filter((col) => col.type !== 'title' && col.type !== 'divider'))
const fullDesc = computed(() => t('mobile.fullSheetDesc', { editable: needFields.value.length }))
/** 出口那一屏的说明:几条出口、其中几条此刻走不了,一句话说完。 */
const routeSheetDesc = computed(() => {
const base = t('mobile.pickRouteHint', { count: routeButtons.value.length })
const blocked = ctx.blockedRoutes.value.length
return blocked ? `${base} · ${t('mobile.routeBlockedCount', { count: blocked })}` : base
})
// 标题会跟着这一环的填写内容改写成什么样,写在同意那一屏的副标题上:
// 这是提交之前的一句话,摆在抬头里却让每张单子都多占一行。
const approveDesc = computed(() => {
const hit = routeButtons.value.find((item) => item.name === ctx.routeName.value)
const to = hit?.target
return [
to ? t('mobile.routeTo', { name: hit?.name ?? '', target: to }) : hit?.name,
detail.value?.serial,
ctx.titleNext.value ? t('task.titleWillUpdate', { title: ctx.titleNext.value }) : ''
]
.filter(Boolean)
.join(' · ')
})
const menuItems = computed<{ key: string; label: string; icon: IconName }[]>(() => {
const items: { key: string; label: string; icon: IconName }[] = []
if (node.value?.allow_add_task) items.push({ key: 'add', label: t('task.addTask'), icon: 'userPlus' })
items.push({ key: 'transfer', label: t('task.transfer'), icon: 'swap' })
if (node.value?.allow_cc !== false) items.push({ key: 'cc', label: t('task.cc'), icon: 'mail' })
if (node.value?.allow_share !== false) items.push({ key: 'share', label: t('task.share'), icon: 'externalLink' })
// 手机上不给打印入口:这一屏是给人批单子用的,打印是回到电脑上干的事,
// 手机上点一下只会把「打印审批单」那一整张桌面版面端到人面前。
items.push({ key: 'full', label: t('mobile.viewFull'), icon: 'document' })
items.push({ key: 'desktop', label: t('mobile.toDesktop'), icon: 'window' })
return items
})
const columns = computed(() => visibleCols.value)
const moneyCol = computed(() => columns.value.find((col) => col.type === 'money' || col.type === 'number'))
const DATE_TYPES = ['date', 'datetime', 'time']
/** 日期不当标题:扫明细的人是先看「这笔钱花在什么上」,日子是那行的小字。 */
const dateCols = computed(() => columns.value.filter((col) => DATE_TYPES.includes(col.type)))
const headCols = computed(() => columns.value.filter((col) => col !== moneyCol.value && !DATE_TYPES.includes(col.type)))
function rowCell(row: Record<string, unknown>, col: FormFieldDef | undefined) {
return col ? fieldText(col, row[col.key]) : ''
}
function rowMoney(row: Record<string, unknown>) {
return rowCell(row, moneyCol.value)
}
/** 明细一条的两行怎么凑:第一行「这是第几条 · 花在什么上 · 多少钱」,第二行才是日子和备注。 */
function rowHead(row: Record<string, unknown>) {
const text = headCols.value.map((col) => rowCell(row, col)).find(Boolean)
// 明细里全是日期和金额时(比如只记天的补贴),标题只能落回日期
return text || dateCols.value.map((col) => rowCell(row, col)).find(Boolean) || ''
}
function rowTail(row: Record<string, unknown>) {
const head = rowHead(row)
return columns.value
.filter((col) => col !== moneyCol.value)
.map((col) => rowCell(row, col))
.filter((cell) => cell && cell !== head)
.join(' · ')
}
/**
* 意见编辑器握在桌面那份逻辑手里(提交时要问它贴图传完没有、办完要让它清草稿)。
* 手机上这颗是另一个实例,所以挂载时把它交回去,别让用户贴的图静静丢掉。
*/
function bindOpinionEditor(el: unknown) {
ctx.bindOpinionEditor(el)
}
function bindRecordPanel(el: unknown) {
ctx.bindRecordPanel(el)
}
/* ------------------------------------------------------------------ 办理 */
function startApprove() {
if (routeButtons.value.length > 1) {
routeSheet.value = true
return
}
const only = routeButtons.value[0]
if (only && !only.ok) {
appStore.warning(t('task.routeConditionUnmet'))
return
}
ctx.routeName.value = only?.name ?? ''
approveSheet.value = true
}
function pickAndApprove(item: TaskRouteButton) {
ctx.pickRoute(item)
if (!ctx.routeName.value) return
routeSheet.value = false
approveSheet.value = true
}
async function approve() {
approveSheet.value = false
await ctx.submit(next)
}
/** 办完不停在原地:手上通常不止一条,直接把人送到下一条待办。 */
async function next() {
const list = await taskAPI.listProcessing({ page: 1, page_size: 2 }).catch(() => null)
const hit = (list?.items ?? []).find((item) => item.id !== taskId.value)
menuOpen.value = false
if (hit) await router.replace({ name: 'todo-detail', params: { id: hit.id } })
else await router.replace({ name: 'my-todo' })
await appStore.refreshBadgeCounts()
}
function backToList() {
if (window.history.length > 1) router.back()
else router.replace({ name: 'my-todo' })
}
/** 从摘要回到「本环节需填写」那块:填到一半被页签切走,回来还能接上。 */
const fillEl = ref<HTMLElement | null>(null)
function backToFill() {
approveSheet.value = false
tabKey.value = 'form'
nextTick(() => fillEl.value?.scrollIntoView({ behavior: 'smooth', block: 'center' }))
}
/* ------------------------------------------------------------------ 换人 / 抄送 */
const peopleModel = computed(() => (ctx.sendShow.value ? ctx.sendPeople.value : ctx.people.value))
const peopleOpinionModel = computed(() => (ctx.sendShow.value ? ctx.sendOpinion.value : ctx.peopleOpinion.value))
function setPeople(value: string[]) {
if (ctx.sendShow.value) ctx.sendPeople.value = value
else ctx.people.value = value
}
function setPeopleOpinion(value: string) {
if (ctx.sendShow.value) ctx.sendOpinion.value = value
else ctx.peopleOpinion.value = value
}
const peopleTitle = computed(() => {
if (ctx.sendShow.value) return ctx.sendMode.value === 'cc' ? t('task.cc') : t('task.share')
return ctx.peopleMode.value === 'add' ? t('task.addTask') : t('task.transfer')
})
const peopleDesc = computed(() => (ctx.sendShow.value && ctx.sendMode.value === 'share' ? t('task.shareHint') : ''))
function closePeople() {
ctx.sendShow.value = false
ctx.peopleShow.value = false
}
async function send() {
await ctx.confirmSend()
if (!ctx.sendShow.value) menuOpen.value = false
}
function runMenu(key: string) {
menuOpen.value = false
if (key === 'full') {
tabKey.value = 'form'
fullOpen.value = true
return
}
if (key === 'desktop') {
pinDesktop(true)
return
}
if (key === 'cc') ctx.openSend('cc')
else if (key === 'share') ctx.openSend('share')
else if (key === 'add') ctx.openAddTask()
else ctx.openTransfer()
}
function closeReader() {
fullOpen.value = false
rowsOpen.value = false
}
/* 从「下一条」换到另一张单子时组件不重新挂载:页签、弹层、阅读器都得自己收回去,
否则上一张单子的意见框还开着,人已经在看另一张单子了。 */
watch(taskId, () => {
tabKey.value = 'form'
approveSheet.value = false
routeSheet.value = false
menuOpen.value = false
closeReader()
window.scrollTo({ top: 0 })
})
</script>

View File

@ -0,0 +1,236 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import type { WorkDetail } from '@/types'
import MobileWorkView from './MobileWorkView.vue'
import { expenseDetail } from './mobileFixtures'
/**
* 手机上的单据详情(已办 / 我发起的 / 待阅 / 通知 / 监控都落到这一屏)。
*
* 盯的是「这一屏只答手机上要答的问题」:现在卡在哪、走到哪了、还能不能推动它。
* 桌面上那四排说明、打印审批单、整屏流程图在这里一律不出现——它们在 390 上只会把
* 真正的答案挤到第三屏。判据本身由 WorkDetailView 算,这里只验摆法与出口。
*/
vi.mock('@/api', () => ({
taskAPI: { press: vi.fn() },
workAPI: { listComments: vi.fn().mockResolvedValue([]) }
}))
vi.mock('@/api/work', () => ({ viewReadsOfJob: vi.fn().mockResolvedValue(null) }))
function router() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/created', name: 'my-created', component: { template: '<div />' } },
{ path: '/work/:job', name: 'work-detail', component: { template: '<div />' } }
]
})
}
async function render(over: Partial<WorkDetail> = {}, props: Record<string, unknown> = {}) {
const r = router()
await r.push('/work/BX-20261103-0142')
await r.isReady()
const detail = expenseDetail(over)
const wrapper = mount(MobileWorkView, {
props: { detail, formSchema: detail.forms[0]!.content, ...props },
global: {
plugins: [r, createPinia(), i18n],
stubs: {
teleport: true,
Teleport: true,
// 这三块各有自己的接口与依赖,是各自的测试该管的事
FormRenderer: true,
ExternalCheckPanel: true,
AttachmentGallery: true
}
}
})
await flushPromises()
return { wrapper }
}
beforeEach(() => {
setActivePinia(createPinia())
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
describe('手机上的单据详情', () => {
it('抬头只说这一单现在怎么样了', async () => {
const { wrapper } = await render({ current_activity_names: '财务总监' })
const head = wrapper.find('[data-test="m-work-head"]').text()
expect(head).toContain('处理中')
expect(head).toContain('财务总监')
expect(head).toContain('黄雪秋')
expect(head).toContain('李明')
// 桌面抬头那三排在手机上重复:流程名 + 单号 + 发起时间 + 按第 N 版设计
expect(head).not.toContain('发起时间')
expect(head).not.toContain('还没排号')
})
it('关键数字上浮,钱第一眼就看到', async () => {
const { wrapper } = await render()
expect(wrapper.find('[data-test="m-work-head"]').text()).toContain('4,860.00')
})
it('没有打印审批单,也没有桌面那张流程图画布', async () => {
const { wrapper } = await render()
const text = wrapper.text()
expect(text).not.toContain('打印审批单')
expect(text).not.toContain('流转流程图')
expect(wrapper.find('[data-test="m-work-tab-form"]').exists()).toBe(true)
expect(wrapper.find('[data-test="m-flow"]').exists()).toBe(false)
})
it('切到审批记录才是那条时间线,单号落在末尾', async () => {
const { wrapper } = await render()
await wrapper.find('[data-test="m-work-tab-progress"]').trigger('click')
const flow = wrapper.find('[data-test="m-flow"]')
expect(flow.exists()).toBe(true)
expect(flow.text()).toContain('王建国')
expect(flow.text()).toContain('BX-20261103-0142')
})
it('底下只在办得动时出现,而且就那一颗', async () => {
const pressing = await render({}, { canPress: true })
expect(pressing.wrapper.find('[data-test="m-work-press"]').exists()).toBe(true)
expect(pressing.wrapper.find('[data-test="m-work-start"]').exists()).toBe(false)
const startable = await render({ can_start: true })
expect(startable.wrapper.find('[data-test="m-work-start"]').exists()).toBe(true)
expect(startable.wrapper.find('[data-test="m-work-press"]').exists()).toBe(false)
// 办不动就整条不挂:底下悬一颗没用的「刷新」,还永远盖着最后两行
const readonly = await render({ status: 'completed', tasks: [] }, { canPress: false })
expect(readonly.wrapper.text()).not.toContain('刷新')
expect(readonly.wrapper.find('[data-test="m-work-start"]').exists()).toBe(false)
expect(readonly.wrapper.find('[data-test="m-work-press"]').exists()).toBe(false)
})
it('终止流程收进「···」,确认时把那句话交出去', async () => {
const { wrapper } = await render({ can_terminate: true })
await wrapper.find('[data-test="m-work-more"]').trigger('click')
const menu = wrapper.find('[data-test="m-work-menu"]')
expect(menu.text()).toContain('终止流程')
expect(menu.text()).toContain('看电脑版')
const item = menu.findAll('button').find((node) => node.text().includes('终止流程'))
await item!.trigger('click')
const sheet = wrapper.find('[data-test="m-work-terminate-sheet"]')
expect(sheet.exists()).toBe(true)
await sheet.find('textarea').setValue('重复提单')
await sheet.find('[data-test="m-work-terminate-confirm"]').trigger('click')
expect(wrapper.emitted('terminate')?.[0]).toEqual(['重复提单'])
})
it('没有终止与干预权限时,「···」里不摆那两颗', async () => {
const { wrapper } = await render()
await wrapper.find('[data-test="m-work-more"]').trigger('click')
const menu = wrapper.find('[data-test="m-work-menu"]').text()
expect(menu).not.toContain('终止流程')
expect(menu).not.toContain('流程干预')
})
it('被挂起的单子先把「为什么办不动」说在最上面', async () => {
const { wrapper } = await render({ paused: true, pause_actor: '管理员', pause_time: '2026-11-03 10:00:00', pause_reason: '等发票核验' })
expect(wrapper.text()).toContain('已挂起')
expect(wrapper.text()).toContain('等发票核验')
})
it('停在开始环节等第三方提交时,提交那颗按下去没用,得先看见原因', async () => {
const { wrapper } = await render({ can_start: true }, { startLocked: true, startLockText: '等待财务系统在外部提交' })
expect(wrapper.text()).toContain('等待财务系统在外部提交')
expect((wrapper.find('[data-test="m-work-start"]').element as HTMLButtonElement).disabled).toBe(true)
})
it('不给刷新按钮:下拉这一把顶上去,切回前台再自己取一次', async () => {
const { wrapper } = await render()
// 顶栏与吸底那一行都没有刷新这颗钮
expect(wrapper.text()).not.toContain('刷新')
expect(wrapper.find('[data-test="m-pull"]').exists()).toBe(false)
Object.defineProperty(window, 'scrollY', { value: 0, writable: true, configurable: true })
const start = new Event('touchstart', { cancelable: true }) as unknown as TouchEvent & { touches: unknown[] }
start.touches = [{ clientY: 100 }]
window.dispatchEvent(start)
const move = new Event('touchmove', { cancelable: true }) as unknown as TouchEvent & { touches: unknown[] }
move.touches = [{ clientY: 260 }]
window.dispatchEvent(move)
await flushPromises()
expect(wrapper.find('[data-test="m-pull"]').text()).toContain('松开刷新')
window.dispatchEvent(new Event('touchend'))
expect(wrapper.emitted('refresh')).toHaveLength(1)
// 从企微切回来(页面重新可见)也算一次
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
document.dispatchEvent(new Event('visibilitychange'))
expect(wrapper.emitted('refresh')).toHaveLength(2)
})
it('给了取数那条路就走它,并且胶囊真的等它取完', async () => {
let done: () => void = () => undefined
const reload = vi.fn(
() =>
new Promise<void>((resolve) => {
done = resolve
})
)
const { wrapper } = await render({}, { reload })
Object.defineProperty(window, 'scrollY', { value: 0, writable: true, configurable: true })
const start = new Event('touchstart', { cancelable: true }) as unknown as TouchEvent & { touches: unknown[] }
start.touches = [{ clientY: 100 }]
window.dispatchEvent(start)
const move = new Event('touchmove', { cancelable: true }) as unknown as TouchEvent & { touches: unknown[] }
move.touches = [{ clientY: 260 }]
window.dispatchEvent(move)
window.dispatchEvent(new Event('touchend'))
expect(reload).toHaveBeenCalledTimes(1)
expect(wrapper.emitted('refresh')).toBeUndefined()
// 还没取完:胶囊停在「正在刷新…」
await flushPromises()
expect(wrapper.find('[data-test="m-pull"]').text()).toContain('正在刷新')
done()
await flushPromises()
expect(wrapper.find('[data-test="m-pull"]').exists()).toBe(false)
})
it('低频那几件收进顶栏的「···」,不占屏幕下沿', async () => {
const { wrapper } = await render({ status: 'completed', tasks: [], can_terminate: false }, { canPress: false })
await wrapper.find('[data-test="m-work-more"]').trigger('click')
expect(wrapper.find('[data-test="m-work-menu"]').text()).toContain('看电脑版')
})
it('摘要按配置摆、末尾又不留那一行时,「完整单据」收进「···」,不是把这单看全的路断了', async () => {
const r = router()
await r.push('/work/BX-20261103-0142')
await r.isReady()
const detail = expenseDetail()
const content = detail.forms[0]!.content
const schema = { ...content, layout: { ...(content.layout ?? {}), mobile: { enabled: true, title: '费用报销基本信息', showFullSheet: false } } }
const wrapper = mount(MobileWorkView, {
props: { detail, formSchema: schema },
global: {
plugins: [r, createPinia(), i18n],
stubs: { teleport: true, Teleport: true, FormRenderer: true, ExternalCheckPanel: true, AttachmentGallery: true }
}
})
await flushPromises()
// 摘要那一屏上不再有那一行
expect(wrapper.text()).not.toContain('完整单据')
await wrapper.find('[data-test="m-work-more"]').trigger('click')
expect(wrapper.find('[data-test="m-work-menu"]').text()).toContain('完整单据')
})
it('没配手机端版式时「···」里不多这一条:那一行本来就在摘要末尾', async () => {
const { wrapper } = await render()
await wrapper.find('[data-test="m-work-more"]').trigger('click')
const menu = wrapper.find('[data-test="m-work-menu"]').text()
expect(menu).not.toContain('完整单据')
expect(wrapper.text()).toContain('完整单据')
})
})

View File

@ -0,0 +1,506 @@
<template>
<div class="min-h-full" :class="canAct ? 'pb-[calc(4.75rem+env(safe-area-inset-bottom))]' : 'pb-8'">
<!-- 顶栏:返回 + 标题 + 「···」。这一档是 chromeless(见 router 上 work-detail 那句),
整块屏由这一页自己管,所以返回得自己给。刷新不给按钮了——下拉这一把手势就够,
加上从企微切回来时自己取一次(见 useMobileRefresh),顶部因此只留真正低频的「···」。 -->
<div class="sticky top-0 z-20 flex h-11 items-center gap-1 bg-white/95 px-1.5 backdrop-blur dark:bg-dark-800/95">
<button
type="button"
class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
:aria-label="t('common.back')"
data-test="m-work-back"
@click="back"
>
<Icon name="arrowLeft" class="h-5 w-5 text-gray-700 dark:text-dark-200" />
</button>
<p class="min-w-0 flex-1 truncate text-[15px] font-semibold text-gray-900 dark:text-white">
{{ detail.title || detail.process_name }}
</p>
<button
type="button"
class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
:aria-label="t('task.moreActions')"
data-test="m-work-more"
@click="menuOpen = true"
>
<Icon name="more" class="h-[18px] w-[18px] text-gray-500 dark:text-dark-400" />
</button>
</div>
<MobilePullPill :state="pullState" />
<!-- 抬头就一行:左边是这张单此刻的状态,右端是谁提的,再往下是关键数字。
桌面上那一整块说明(按第 N 版设计 / 流程名 · 单号 · 发起人:×(部门) / 发起时间)
在手机上一个字都不摆——那些是「这张单是怎么来的」,列表里刚读过;
这一屏要答的是「现在怎么样了」,谁提的压成一枚人标挂在同一行右端就够,
发起时间、单号、流转全过程都在「审批记录」那一栏的第一行和最后一行。 -->
<div class="bg-white px-4 pb-3 pt-2 dark:bg-dark-800" data-test="m-work-head">
<div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">
<span :class="badgeClass(workStatusVariant(detail.status))">{{ workStatusLabel(detail.status) }}</span>
<span v-if="detail.current_activity_names" class="badge badge-primary">{{ detail.current_activity_names }}</span>
<span v-if="detail.paused" class="badge badge-warning">{{ t('monitor.intervene.paused') }}</span>
<span v-if="detail.tasks.length" class="badge badge-gray">
{{ t('task.currentHandler') }}:{{ handlerText }}
</span>
<span class="ml-auto flex min-w-0 items-center gap-1.5 text-[13px] text-gray-500 dark:text-dark-400">
<span
class="flex h-[18px] w-[18px] flex-shrink-0 items-center justify-center rounded-full bg-primary-100 text-[10px] font-medium text-primary-700 dark:bg-primary-900/60 dark:text-primary-300"
>
{{ (detail.creator_person || '').slice(0, 1) }}
</span>
<span class="min-w-0 truncate">{{ detail.creator_person || '--' }}</span>
<span v-if="detail.creator_unit_name" class="hidden truncate sm:inline">· {{ detail.creator_unit_name }}</span>
</span>
</div>
<div v-if="plan.floats.length" class="mt-2.5 flex gap-7 overflow-x-auto border-t border-gray-100 pt-2.5 dark:border-dark-700">
<div v-for="row in plan.floats" :key="row.field.key" class="flex-shrink-0">
<p class="text-[11px] text-gray-400 dark:text-dark-500">{{ row.field.label }}</p>
<p class="num mt-0.5 whitespace-nowrap text-[19px] font-bold leading-tight text-gray-900 dark:text-white">{{ row.text }}</p>
</div>
</div>
</div>
<!-- 这一单此刻办得动吗:挂起、被第三方锁住、停在开始环节等提交,各说一句 -->
<div class="space-y-2 px-3.5 pt-2">
<p v-if="detail.paused" class="flex items-start gap-2 rounded-xl bg-amber-50 px-3 py-2.5 text-[13px] text-amber-800 dark:bg-amber-900/25 dark:text-amber-200">
<Icon name="pause" class="mt-0.5 h-4 w-4 flex-shrink-0" />
<span class="min-w-0 flex-1">
{{ t('monitor.intervene.pausedBy', { actor: detail.pause_actor || '-', time: formatDateTimeToMinute(detail.pause_time || '') }) }}
<span v-if="detail.pause_reason"> · {{ detail.pause_reason }}</span>
</span>
</p>
<p v-if="startLocked" class="flex items-start gap-2 rounded-xl bg-indigo-50 px-3 py-2.5 text-[13px] leading-relaxed text-indigo-900 dark:bg-indigo-900/25 dark:text-indigo-100">
<Icon name="lock" class="mt-0.5 h-4 w-4 flex-shrink-0" />{{ startLockText }}
</p>
<div
v-for="item in beginDecisions"
:key="item.id"
class="rounded-xl bg-indigo-50 px-3.5 py-3 text-[13px] text-indigo-900 dark:bg-indigo-900/25 dark:text-indigo-100"
>
<p class="font-medium leading-relaxed">{{ t('work.atBeginDecisionBanner', { app: item.appName || item.app, route: item.route }) }}</p>
<p v-if="item.opinion" class="mt-1 leading-relaxed">{{ t('work.atBeginDecisionOpinion', { opinion: item.opinion }) }}</p>
<div class="mt-2 flex gap-2">
<button type="button" class="btn btn-primary btn-sm flex-1" @click="emit('confirmDecision', item.id)">
{{ t('work.atBeginDecisionConfirm') }}
</button>
<button type="button" class="btn btn-secondary btn-sm" @click="emit('rejectDecision', item.id)">
{{ t('work.atBeginDecisionReject') }}
</button>
</div>
</div>
</div>
<!-- 两页签:填了什么、走到哪了。桌面上那个「流转流程图」画布在手机上换成进度时间线 -->
<div class="sticky top-11 z-20 mt-2 flex gap-5 border-b border-gray-100 bg-white px-4 dark:border-dark-700 dark:bg-dark-800">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
class="relative py-2.5 text-sm"
:class="tabKey === tab.key ? 'font-semibold text-gray-900 dark:text-white' : 'text-gray-400 dark:text-dark-500'"
:data-test="`m-work-tab-${tab.key}`"
@click="tabKey = tab.key"
>
{{ tab.label }}
<span v-if="tab.count" class="num ml-0.5 text-[11px] opacity-70">{{ tab.count }}</span>
<span v-if="tabKey === tab.key" class="absolute inset-x-0 -bottom-px h-0.5 rounded bg-primary-600"></span>
</button>
</div>
<div class="space-y-2 px-3.5 py-3">
<template v-if="tabKey === 'form'">
<div class="empty:hidden">
<ExternalCheckPanel :job="detail.job" :readonly="detail.status !== 'running'" @changed="emit('refresh')" />
</div>
<MobileFormSummary
:plan="plan"
:data="detail.data"
:job="detail.job"
:activity="detail.activity"
@open-rows="rowsOpen = true"
@open-full="fullOpen = true"
/>
<MobileFold
v-if="detail.attachments.length"
icon="paperclip"
:title="t('task.attachments')"
:note="t('mobile.flowFiles', { count: detail.attachments.length })"
>
<div class="px-3.5 py-3">
<AttachmentGallery :items="detail.attachments" />
</div>
</MobileFold>
</template>
<div v-else class="rounded-xl bg-white px-3.5 py-3 shadow-sm dark:bg-dark-800">
<MobileFlow
:items="detail.task_completed"
:routes="detail.routes"
:pending="detail.tasks"
:start="startRecord"
:comments="comments"
:logs="detail.work_logs"
:my-identity="myIdentity"
:serial="detail.serial || ''"
/>
</div>
</div>
<!-- 吸底:这一单办得动才出现,而且就那一颗。没得办的时候整条不挂——
底下凭空悬一颗「刷新」既没内容可刷,又把最后两行永远盖住一半。 -->
<div
v-if="canAct"
class="fixed inset-x-0 bottom-0 z-20 flex items-center gap-2 border-t border-gray-100 bg-white/95 px-3.5 pb-[calc(0.625rem+env(safe-area-inset-bottom))] pt-2.5 backdrop-blur dark:border-dark-700 dark:bg-dark-800/95"
>
<button
v-if="detail.can_start"
type="button"
class="btn btn-primary flex-1"
:disabled="startLocked"
:title="startLocked ? startLockText : ''"
data-test="m-work-start"
@click="startSheet = true"
>
<Icon name="paperAirplane" class="mr-1 h-4 w-4" />{{ t('work.startNow') }}
</button>
<button
v-else-if="canPress"
type="button"
class="btn btn-primary flex-1"
data-test="m-work-press"
@click="emit('press')"
>
<Icon name="bell" class="mr-1 h-4 w-4" />{{ t('task.press') }}
</button>
</div>
<MobileSheet :show="menuOpen" test="m-work-menu" :title="t('task.moreActions')" @close="menuOpen = false">
<div class="pb-1">
<button
v-for="item in menuItems"
:key="item.key"
type="button"
class="flex w-full items-center gap-2.5 border-b border-gray-50 py-3 text-left text-[14px] text-gray-900 last:border-0 active:bg-gray-50 dark:border-dark-700/40 dark:text-white dark:active:bg-dark-700/50"
:class="item.disabled ? 'cursor-not-allowed opacity-50 active:bg-transparent' : ''"
:disabled="item.disabled"
@click="runMenu(item.key)"
>
<Icon :name="item.icon" class="h-[18px] w-[18px] flex-shrink-0 text-gray-500 dark:text-dark-400" />
<span class="min-w-0 flex-1">
{{ item.label }}
<span v-if="item.hint" class="mt-0.5 block text-[12px] leading-snug text-gray-400 dark:text-dark-400">
{{ item.hint }}
</span>
</span>
</button>
<div class="mt-3 flex items-center gap-2">
<span class="flex-1 text-[13px] text-gray-500 dark:text-dark-400">{{ t('mobile.fontScale') }}</span>
<div class="flex overflow-hidden rounded-lg border border-gray-200 dark:border-dark-600">
<button
v-for="opt in fontOptions"
:key="opt.value"
type="button"
class="border-r border-gray-200 px-2.5 py-1 text-[12px] last:border-0 dark:border-dark-600"
:class="
fontScale === opt.value
? 'border-primary-500 bg-white text-primary-700 dark:bg-dark-800'
: 'border-gray-200 text-gray-500 dark:border-dark-600'
"
@click="setFontScale(opt.value)"
>
{{ opt.label }}
</button>
</div>
</div>
</div>
</MobileSheet>
<!-- 完整单据 / 明细:摘要看不全时的那条兜底路,与待办详情那一屏同一套摆法 -->
<MobileSheet
:show="fullOpen || rowsOpen"
test="m-work-reader"
:title="fullOpen ? t('mobile.viewFull') : plan.table?.field.label || ''"
:desc="fullOpen ? t('mobile.fullSheetReadonly') : ''"
full
@close="closeReader"
>
<div class="pb-1">
<MobileFormReader
v-if="fullOpen"
:schema="formSchema"
:data="detail.data"
:job="detail.job"
:activity="detail.activity"
/>
<div v-else-if="plan.table" class="space-y-2">
<div v-for="(row, index) in tableRows" :key="index" class="rounded-xl bg-white px-3.5 py-3 dark:bg-dark-800">
<p class="flex items-baseline gap-2">
<span class="num text-xs text-gray-400 dark:text-dark-500">{{ t('mobile.rowIndex', { index: index + 1 }) }}</span>
<span class="min-w-0 flex-1 truncate text-[15px] font-medium text-gray-900 dark:text-white">{{ rowHead(row) }}</span>
<span v-if="rowMoney(row)" class="num flex-shrink-0 text-[15px] font-semibold text-gray-900 dark:text-white">{{ rowMoney(row) }}</span>
</p>
<p v-if="rowTail(row)" class="mt-1.5 text-xs text-gray-400 dark:text-dark-500">{{ rowTail(row) }}</p>
</div>
</div>
</div>
</MobileSheet>
<!-- 终止与提交都要写一句话:这一档也做成下推层,与待办详情那一屏同一个手感 -->
<MobileSheet :show="startSheet" test="m-work-start-sheet" :title="t('work.startNow')" @close="startSheet = false">
<p class="text-[13px] leading-relaxed text-gray-600 dark:text-dark-300">{{ t('work.atBeginStartConfirm') }}</p>
<div class="mt-3">
<TextArea v-model="startOpinion" :rows="3" :placeholder="t('task.opinionPlaceholder')" />
</div>
<template #footer>
<button type="button" class="btn btn-secondary flex-1" @click="startSheet = false">{{ t('common.cancel') }}</button>
<button
type="button"
class="btn btn-primary flex-1"
data-test="m-work-start-confirm"
@click="submitStart"
>
{{ t('common.confirm') }}
</button>
</template>
</MobileSheet>
<MobileSheet :show="terminateSheet" test="m-work-terminate-sheet" :title="t('task.terminate')" @close="terminateSheet = false">
<p class="text-[13px] leading-relaxed text-gray-600 dark:text-dark-300">{{ t('task.terminateConfirm') }}</p>
<div class="mt-3">
<label class="input-label">{{ t('task.terminateReason') }}</label>
<TextArea v-model="terminateOpinion" :rows="3" :placeholder="t('task.terminateReasonPlaceholder')" />
<p class="mt-1 text-[12px] leading-snug text-gray-400 dark:text-dark-400">{{ t('task.terminateReasonRequired') }}</p>
</div>
<template #footer>
<button type="button" class="btn btn-secondary flex-1" @click="terminateSheet = false">{{ t('common.cancel') }}</button>
<button
type="button"
class="btn btn-danger flex-1"
data-test="m-work-terminate-confirm"
:disabled="!terminateOpinion.trim()"
@click="submitTerminate"
>
{{ t('common.confirm') }}
</button>
</template>
</MobileSheet>
</div>
</template>
<script setup lang="ts">
/**
* 单据详情(`/work/:job`)在手机上那一屏。
*
* 这一页是「已办 / 我发起的 / 待阅 / 通知 / 流程监控」共同的落点,原先只有桌面那一版:
* 抬头四排说明 + 表单整屏摊开 + 一张桌面流程图,在 390 上划三屏还没看到进度。手机上换成
* 与待办详情同一套语言——抬头两行、摘要按节折叠、进度换成竖向时间线、动作收进吸底那一行。
* 只读这一档由这一页自己管:没有待办要办,所以没有意见框,也没有提交那条链路。
* 桌面上那一版(`views/oa/WorkDetailView.vue`)照原样,一个字段都没少。
*/
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
import AttachmentGallery from '@/components/oa/AttachmentGallery.vue'
import ExternalCheckPanel from '@/components/oa/ExternalCheckPanel.vue'
import MobileFlow from './MobileFlow.vue'
import MobileFold from './MobileFold.vue'
import MobileFormReader from './MobileFormReader.vue'
import MobileFormSummary from './MobileFormSummary.vue'
import MobileSheet from './MobileSheet.vue'
import MobilePullPill from './MobilePullPill.vue'
import TextArea from '@/components/common/TextArea.vue'
import { planForm, fieldText } from './useFormPlan'
import { useMobileShell, type FontScale } from '@/composables/useMobileShell'
import { usePullToRefresh, useRefreshOnReturn } from '@/composables/useMobileRefresh'
import { landingPath } from '@/utils/returnPath'
import { formatDateTimeToMinute } from '@/utils/format'
import { badgeClass, workStatusLabel, workStatusVariant } from '@/utils/oa'
import { personText } from '@/utils/personLabel'
import type { ApprovalStartLike } from '@/utils/approvalRecord'
import type { FormSchema, NodeDecisionView, WorkComment, WorkDetail } from '@/types'
const props = withDefaults(
defineProps<{
detail: WorkDetail
formSchema: FormSchema | null
comments?: WorkComment[]
myIdentity?: string
startRecord?: ApprovalStartLike | null
canPress?: boolean
canIntervene?: boolean
startLocked?: boolean
startLockText?: string
beginDecisions?: NodeDecisionView[]
/** 真去取一次的那条路:给了它,下拉那枚胶囊才会转到「正在刷新…」直到取完 */
reload?: (() => unknown) | null
}>(),
{
comments: () => [],
myIdentity: '',
startRecord: null,
canPress: false,
canIntervene: false,
startLocked: false,
startLockText: '',
beginDecisions: () => [],
reload: null
}
)
const emit = defineEmits<{
refresh: []
press: []
/** 这两颗都要带上那一句话:意见在手机上就在下推层里写,父页只管交给后端 */
start: [opinion: string]
terminate: [opinion: string]
intervene: []
confirmDecision: [id: string]
rejectDecision: [id: string]
}>()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const { fontScale, setFontScale, pinDesktop } = useMobileShell()
type TabKey = 'form' | 'progress'
type IconName = InstanceType<typeof Icon>['$props']['name']
const tabKey = ref<TabKey>('form')
const menuOpen = ref(false)
const fullOpen = ref(false)
const rowsOpen = ref(false)
const startSheet = ref(false)
const terminateSheet = ref(false)
const startOpinion = ref('')
const terminateOpinion = ref('')
const plan = computed(() => planForm(props.formSchema, { data: props.detail.data }))
const tabs = computed(() => [
{ key: 'form' as TabKey, label: t('work.formData'), count: 0 },
{ key: 'progress' as TabKey, label: t('task.approvalHistory'), count: props.detail.task_completed.length }
])
const handlerText = computed(() =>
props.detail.tasks
.slice(0, 2)
.map((item) => item.identity_name || personText(item.identity))
.join('、')
)
const terminateHint = computed(() => String(props.detail.terminate_hint ?? ''))
const menuItems = computed<
{ key: string; label: string; icon: IconName; disabled?: boolean; hint?: string }[]
>(() => {
const items: { key: string; label: string; icon: IconName; disabled?: boolean; hint?: string }[] = []
if (props.canIntervene) items.push({ key: 'intervene', label: t('monitor.intervene.entry'), icon: 'shuffle' })
// 终止这一条跟桌面端同一套两档挡法:流程那一格整个关掉「发起人终止」就不出现;
// 只是过了设定的窗口,仍旧列出来但按不动,下面跟一句为什么。判据在后端一处算
// (engine.terminate_blocker → service/terminate.py),界面不自己再判一遍。
if (props.detail.status === 'running' && (props.detail.can_terminate || Boolean(terminateHint.value))) {
items.push({
key: 'terminate',
label: t('task.terminate'),
icon: 'ban',
disabled: !props.detail.can_terminate,
hint: terminateHint.value
})
}
// 摘要按配置摆、末尾又不留「完整单据」那一行时,这一屏原本就没第二条路了:
// 配表的人要的是"只有一节",不是"这一单在手机上看不全",所以把入口收进「···」,
// 不再让它占住那一屏。待办那一屏的「···」本来就有这一条,两屏对齐。
if (plan.value.custom && !plan.value.showFull) {
items.push({ key: 'full', label: t('mobile.viewFull'), icon: 'document' })
}
items.push({ key: 'desktop', label: t('mobile.toDesktop'), icon: 'window' })
return items
})
// 只有「这一单此刻能被推动」才值得占住屏幕下沿
const canAct = computed(() => props.detail.can_start || props.canPress)
// 这一屏没有输入框,刷新永远不会吃掉谁写了一半的字,所以回到前台也敢自己取一次
function refresh() {
return props.reload ? props.reload() : emit('refresh')
}
const { state: pullState } = usePullToRefresh(refresh)
useRefreshOnReturn(refresh)
const fontOptions = computed<{ value: FontScale; label: string }[]>(() => [
{ value: 'm', label: t('mobile.fontM') },
{ value: 'l', label: t('mobile.fontL') },
{ value: 'xl', label: t('mobile.fontXL') }
])
const tableRows = computed<Record<string, unknown>[]>(() => {
const field = plan.value.table?.field
const value = field ? (props.detail.data as Record<string, unknown>)[field.key] : null
return Array.isArray(value) ? (value as Record<string, unknown>[]) : []
})
const tableCols = computed(() =>
(plan.value.table?.field.columns ?? []).filter((col) => col.type !== 'title' && col.type !== 'divider')
)
const DATE_TYPES = ['date', 'datetime', 'time']
const moneyCol = computed(() => tableCols.value.find((col) => col.type === 'money' || col.type === 'number'))
const headCol = computed(() => tableCols.value.find((col) => !DATE_TYPES.includes(col.type) && col !== moneyCol.value))
const tailCols = computed(() => tableCols.value.filter((col) => col !== headCol.value && col !== moneyCol.value))
function rowHead(row: Record<string, unknown>): string {
return headCol.value ? fieldText(headCol.value, row[headCol.value.key]) || '--' : '--'
}
function rowMoney(row: Record<string, unknown>): string {
return moneyCol.value ? fieldText(moneyCol.value, row[moneyCol.value.key]) : ''
}
function rowTail(row: Record<string, unknown>): string {
return tailCols.value
.map((col) => fieldText(col, row[col.key]))
.filter(Boolean)
.join(' · ')
}
function submitStart() {
startSheet.value = false
emit('start', startOpinion.value)
startOpinion.value = ''
}
function submitTerminate() {
const opinion = terminateOpinion.value.trim()
if (!opinion) return
terminateSheet.value = false
emit('terminate', opinion)
terminateOpinion.value = ''
}
function closeReader() {
fullOpen.value = false
rowsOpen.value = false
}
function runMenu(key: string) {
menuOpen.value = false
if (key === 'full') {
tabKey.value = 'form'
fullOpen.value = true
return
}
if (key === 'intervene') emit('intervene')
else if (key === 'terminate') terminateSheet.value = true
else if (key === 'desktop') {
// 钉到电脑版并把这一页留着:他要看的是这张单子的完整版面,不是被甩回列表
pinDesktop(true)
void router.replace(route.fullPath)
}
}
function back() {
if (window.history.length > 1) router.back()
else void router.replace(landingPath())
}
</script>

View File

@ -0,0 +1,334 @@
/**
* 手机版式那几份「假单子」。
*
* 为什么要有:手机版式的价值全在「一张四十几个字段的单子被读成什么样」,光看代码看不出来,
* 得真摆出来看。这份假单子是照着真实报销单抄的结构——两个分隔条分三节、四十七格里有一多半
* 是空的、系统取数占了六格、明细十二行、发票两张、这一环还要审批人补两点。
* 测试和 playground 都从这里拿,改一处两边都跟着改。
*/
import { computed, ref } from 'vue'
import type { TaskView } from './taskContext'
import type { FormFieldDef, FormSchema, WorkDetail } from '@/types'
export const EXPENSE_FIELDS: FormFieldDef[] = [
{ key: 'serial_no', label: '单据编号', type: 'auto' },
{ key: 'starter', label: '发起人', type: 'auto' },
{ key: 'starter_no', label: '发起人工号', type: 'auto' },
{ key: 'starter_dept', label: '发起部门', type: 'auto' },
{ key: 'leader', label: '行政上级', type: 'auto' },
{ key: 'flow_name', label: '流程名称', type: 'auto' },
{ key: 'sec_base', label: '一、报销基本信息', type: 'divider' },
{ key: 'reason', label: '报销事由', type: 'textarea' },
{ key: 'amount', label: '报销金额', type: 'money', unit: '元' },
{ key: 'approved', label: '核准金额', type: 'money', unit: '元' },
{ key: 'days', label: '出差天数', type: 'number' },
{ key: 'trip', label: '出差行程', type: 'text' },
{ key: 'city', label: '目的地', type: 'text' },
{ key: 'empty_note', label: '备注', type: 'textarea' },
{ key: 'secret', label: '内部编号', type: 'text' },
{ key: 'sec_detail', label: '二、费用明细', type: 'divider' },
{
key: 'rows',
label: '费用明细',
type: 'table',
columns: [
{ key: 'date', label: '日期', type: 'date' },
{ key: 'item', label: '费用事项', type: 'text' },
{ key: 'money', label: '金额', type: 'money' },
{ key: 'note', label: '备注', type: 'text' }
]
},
{ key: 'sec_bill', label: '三、票据', type: 'divider' },
{ key: 'invoices', label: '发票', type: 'attachment' },
{ key: 'contracts', label: '合同或审批件', type: 'attachment' },
{ key: 'signed', label: '发起人签名', type: 'signature' }
]
export function expenseSchema(): FormSchema {
return { fields: EXPENSE_FIELDS, layout: { columns: 3 } }
}
/** 明细那十二条:手机上收成一行「12 条 · 合计」,点开才是逐条。 */
export function expenseRows() {
const items = ['高铁上海→北京往返二等座', '北京市内交通', '住宿两晚', '客户餐费', '打印及杂费']
return Array.from({ length: 12 }, (_, i) => ({
date: `2026-11-0${(i % 3) + 5}`,
item: items[i % items.length],
money: [1129, 86, 1280, 420, 68][i % items.length],
note: i % 4 === 0 ? '电子发票已验真' : ''
}))
}
export function expenseData(): Record<string, unknown> {
return {
serial_no: 'BX-20261103-0142',
starter: '李明',
starter_no: 'DSH10241',
starter_dept: '软件开发事业部',
leader: '黄雪秋',
flow_name: '费用报销',
reason:
'上海—北京客户巡访(华宇、中科讯两家),11/10 至 11/12 出差。样机验收与验收单签字,本次行程已提前在 OA 申请并获批(SQ-20261028-0031),返程后补录票据。',
amount: 4860,
approved: 4800,
days: 3,
trip: '上海—北京客户巡访',
city: '北京',
empty_note: '',
secret: '已作废的内部编号',
rows: expenseRows(),
invoices: [
{ id: 'att-1', name: '高铁票-上海北京.jpg', extension: 'jpg', length: 284160, is_image: true },
{ id: 'att-2', name: '住宿发票.pdf', extension: 'pdf', length: 128400 }
],
contracts: [{ id: 'att-3', name: '出差申请批准件.pdf', extension: 'pdf', length: 96200 }],
// 真是一张小图,不是一个前缀:手机上这一格直接把图画出来,空壳看着就像坏了
signed: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAAAcCAYAAADC8vmmAAAAgElEQVR42u3XMQ6AMAxDUW7CzhG4/71gYulEIK2q9Fnq2Er5sh1124iIaArtx3k9B40GCChfgbSXqtH8PVMUUHWg6TaNAkVwFcf1Guyt40SJ43JBle2eEY5T3sF3SgPLgu2bsGLsRkVyKWC2YweAOisAgZNESkHTbFFEw2bLg3UDxBXsu5pjBLcAAAAASUVORK5CYII='
}
}
export function expenseDetail(over: Partial<WorkDetail> = {}): WorkDetail {
const data = expenseData()
const task = {
id: 'task-1',
job: 'BX-20261103-0142',
work: 'work-1',
title: '差旅报销 · 上海—北京客户巡访',
status: 'running',
process: 'p-expense',
process_name: '费用报销',
serial: 'BX-20261103-0142',
activity: 'a-gm',
activity_name: '总经理审批',
activity_type: 'approve',
identity: 'huangxq',
identity_name: '黄雪秋',
unit_name: '总裁办',
creator_person: '李明',
route_name: '同意',
route_name_list: ['同意', '退回修改'],
form: 'f-expense',
start_time: '2026-11-03 09:20:00',
expire_time: '2026-11-04 18:00:00',
expired: false,
press_count: 2,
view_time: ''
}
return {
id: 'work-1',
job: 'BX-20261103-0142',
serial: 'BX-20261103-0142',
title: '差旅报销 · 上海—北京客户巡访',
status: 'running',
process: 'p-expense',
process_name: '费用报销',
data,
creator: 'p-1',
creator_person: '李明',
creator_unit_name: '软件开发事业部',
activity: 'a-gm',
activity_name: '总经理审批',
start_time: '2026-11-03 09:20:00',
tasks: [{ ...task }],
task,
task_completed: [
{
id: 'done-1',
job: 'BX-20261103-0142',
title: '差旅报销 · 上海—北京客户巡访',
serial: 'BX-20261103-0142',
activity: 'a-dept',
activity_name: '部门审批',
identity: 'wangjg',
identity_name: '王建国',
route_name: '同意',
opinion: '行程与申请一致,同意。',
completed_time: '2026-11-03 10:05:00',
start_time: '2026-11-03 09:20:00',
duration: 45,
status: 'completed',
attachments: [],
form_changes: []
}
],
work_logs: [],
attachments: [{ id: 'att-9', name: '行程单.pdf', extension: 'pdf', length: 88200, type: '', job: '', work: '', activity_name: '部门审批', person_name: '李明', create_time: '', download_url: '' }],
forms: [{ id: 'f-expense', name: '费用报销单', alias: '', description: '', process: 'p-expense', version: 3, content: expenseSchema() }],
activities: [
{ id: 'a-begin', name: '提交', type: 'begin', alias: '' },
{ id: 'a-dept', name: '部门审批', type: 'approve', alias: '' },
{ id: 'a-gm', name: '总经理审批', type: 'approve', alias: '' },
{ id: 'a-finance', name: '财务复核', type: 'approve', alias: '' }
],
activity_nodes: {
'a-gm': {
id: 'a-gm',
name: '总经理审批',
type: 'approve',
form: 'f-expense',
form_perms: { approved: 'editable', reason: 'readonly', secret: 'hidden', days: 'required' },
allow_go_back: true,
allow_add_task: true,
allow_cc: true,
allow_share: true,
allow_comment: true
}
},
routes: [
{ id: 'r-1', name: '同意', from: 'a-gm', to: 'a-finance', to_name: '财务复核', decision: 'agree' },
{ id: 'r-2', name: '退回修改', from: 'a-gm', to: 'a-begin', to_name: '提交', decision: 'reject' }
],
route_guards: { 'r-1': true, 'r-2': true },
flow: { nodes: {}, routes: [] },
can_process: true,
...over
} as unknown as WorkDetail
}
/**
* 一份够用的 TaskView:真的 ref 都给上,动作只记账不真打接口。
*
* 手机版式之所以能被这样测,正是因为它自己不判断任何事:它只把 TaskDetailView 交出的
* 那份东西摆出来。所以这里给的 ref 是什么,屏上就该是什么。
*/
export function stubView(
detail: WorkDetail = expenseDetail(),
over: { requiredMissing?: string[]; frozen?: boolean; handleLocked?: boolean; blocked?: string[] } = {}
): TaskView & { calls: { name: string; at?: unknown }[] } {
const calls: { name: string; at?: unknown }[] = []
const routeName = ref('')
// 弹层那几组状态先提成局部变量:下面那几个 open* 要真的把它们翻开,
// 挂在返回对象里的 ref 可没有被外面直接改写的名字。
const goBackShow = ref(false)
const goBackActivity = ref('')
const goBackWay = ref('step')
const goBackOpinion = ref('')
const peopleShow = ref(false)
const peopleMode = ref<'add' | 'transfer'>('add')
const people = ref<string[]>([])
const peopleOpinion = ref('')
const sendShow = ref(false)
const sendMode = ref<'cc' | 'share'>('cc')
const sendPeople = ref<string[]>([])
const sendOpinion = ref('')
const sendRequiresAction = ref(false)
return {
calls,
detail: ref(detail),
loading: ref(false),
busy: ref(false),
task: computed(() => detail.task ?? null),
canProcess: computed(() => Boolean(detail.can_process && detail.task)),
frozen: computed(() => Boolean(over.frozen)),
node: computed(() => detail.activity_nodes[detail.task?.activity ?? '']),
fieldPerms: computed(() => detail.activity_nodes[detail.task?.activity ?? '']?.form_perms ?? {}),
atBegin: computed(() => false),
formSchema: computed(() => detail.forms[0]?.content ?? null),
formData: ref({ ...detail.data }),
opinion: ref(''),
titleNext: ref(''),
writebackBlocked: computed(() => false),
writebackNote: computed(() => ''),
oaLockText: computed(() => ''),
handleLocked: computed(() => Boolean(over.handleLocked)),
goBackLocked: computed(() => false),
nodeDecisions: computed(() => []),
routeButtons: computed(() =>
[
{ name: '同意', rows: [], ok: true, target: '财务复核' },
{ name: '退回修改', rows: [], ok: true, target: '提交' }
].map((item) => ({ ...item, ok: !(over.blocked ?? []).includes(item.name) }))
),
// 与桌面同一句判据:走不通的就是 ok 为 false 的那几条,不另算一遍
blockedRoutes: computed(() =>
['同意', '退回修改'].filter((name) => (over.blocked ?? []).includes(name)).map((name) => ({ name, rows: [], ok: false, target: '' }))
),
routeName,
// 桌面那份 pickRoute 干的就是「把选中的那条记下来」,这里照做,
// 免得测试里点完出口还得自己补一句状态。
// 桌面那份 pickRoute 干的是「条件不成立就挡回来,否则把选中的那条记下来」,这里照做,
// 免得测试里点完出口还得自己补一句状态,更免得假逻辑比真逻辑宽松。
pickRoute: ((item: { name: string }) => {
calls.push({ name: 'pickRoute', at: item.name })
if ((over.blocked ?? []).includes(item.name)) return
routeName.value = item.name
}) as TaskView['pickRoute'],
requiredMissing: computed(() => over.requiredMissing ?? []),
submit: (async (done?: unknown) => {
calls.push({ name: 'submit' })
if (typeof done === 'function') (done as () => void)()
}) as TaskView['submit'],
goBackShow,
goBackActivity,
goBackWay,
goBackOpinion,
goBackOptions: computed(() => [{ value: '', label: '上一环节' }, { value: 'a-dept', label: '部门审批' }]),
goBackWayOptions: computed(() => [
{ value: 'step', label: '逐级退回' },
{ value: 'jump', label: '直退到该环节' }
]),
openGoBack: (async () => {
calls.push({ name: 'openGoBack' })
goBackActivity.value = ''
goBackWay.value = 'step'
goBackShow.value = true
}) as TaskView['openGoBack'],
confirmGoBack: (async () => {
calls.push({ name: 'confirmGoBack' })
}) as TaskView['confirmGoBack'],
peopleShow,
peopleMode,
people,
peopleOpinion,
addWay: ref('after'),
addMode: ref('together'),
// 桌面那几个 open* 除了记账还会把对应面板打开,这里照做,
// 预览台才能只点一下导航就停在要看的层上。
openAddTask: ((() => {
calls.push({ name: 'openAddTask' })
peopleMode.value = 'add'
people.value = []
peopleOpinion.value = ''
peopleShow.value = true
}) as TaskView['openAddTask']),
openTransfer: ((() => {
calls.push({ name: 'openTransfer' })
peopleMode.value = 'transfer'
people.value = []
peopleOpinion.value = ''
peopleShow.value = true
}) as TaskView['openTransfer']),
confirmPeople: (async () => {
calls.push({ name: 'confirmPeople' })
}) as TaskView['confirmPeople'],
sendShow,
sendMode,
sendPeople,
sendOpinion,
sendRequiresAction,
openSend: ((mode: string) => {
calls.push({ name: 'openSend', at: mode })
sendMode.value = mode as 'cc' | 'share'
sendPeople.value = []
sendOpinion.value = ''
sendRequiresAction.value = false
sendShow.value = true
}) as TaskView['openSend'],
confirmSend: (async () => {
calls.push({ name: 'confirmSend' })
}) as TaskView['confirmSend'],
comments: ref([]),
canComment: computed(() => true),
startRecord: computed(() => ({ activity: '提交', person: '李明', unit: '软件开发事业部', identity: 'liming', time: '2026-11-03 09:20:00' })),
confirmComment: (async () => undefined) as TaskView['confirmComment'],
removeComment: (async () => undefined) as TaskView['removeComment'],
bindOpinionEditor: () => undefined,
bindRecordPanel: () => undefined,
myIdentity: computed(() => 'huangxq'),
reload: (async () => {
calls.push({ name: 'reload' })
}) as TaskView['reload'],
confirmDecision: (async () => undefined) as TaskView['confirmDecision'],
rejectDecision: (async () => undefined) as TaskView['rejectDecision']
}
}

View File

@ -0,0 +1,134 @@
import type { ComputedRef, InjectionKey, Ref } from 'vue'
import type { ActivityNodeBrief, FormSchema, NodeDecisionView, TaskItem, WorkComment, WorkDetail } from '@/types'
import type { ApprovalStartLike, RecordCommentPayload } from '@/utils/approvalRecord'
/** 一条出口:后端给的路线 + 这一环此刻走不走得通 */
export interface TaskRouteOption {
id: string
name: string
from: string
to: string
to_name: string
decision: string
ok: boolean
}
/**
* 待办上的一个按钮 = 同名出口合并后的结果。
*
* 口径只有一份(TaskDetailView 里那段注释说的就是它):设计器允许同一环节画几条同名出口,
* 意思是「同一个动作,去哪由条件决定」,审批人只按一次钮。手机版式要是不参与这次合并,
* 就会出现「电脑上是一个钮、手机上是三个钮」,那已经不是难看不论了。
*/
export interface TaskRouteButton {
name: string
rows: TaskRouteOption[]
ok: boolean
target: string
}
/** 办完之后的去向。桌面是「去已办」,手机是「下一条待办」,所以由调用方给。 */
export type DoneCallback = () => void
/**
* 一张待办在两种版式之间共享的那一份「事实 + 动作」。
*
* 为什么要有这个文件:手机上另写一个审批页最省事的写法,是把 TaskDetailView 的脚本照抄一份
* 再换个模板。抄的那一刀就是裂缝的开始——出口合并、必填那道闸、写回卡控、OA 按钮锁定、
* 表单附件随行提交,桌面每补一处,手机就静悄悄地少一处,而且两边都跑得通、没人会发现。
* 所以这里只让桌面**交出**它已经算好的东西:手机版式拿到的是同一批 computed 和同一批函数,
* 它只负责摆,不参与判断。桌面能批的单子,手机上必然能批。
*
* 加字段时请连着想清楚第二件事:这个值手机版式真的要用吗?用不上就别塞进来,
* ctx 越长,「桌面改了手机没改」的缝隙越难找。
*/
export interface TaskView {
/* 数据 */
detail: Ref<WorkDetail | null>
loading: Ref<boolean>
busy: Ref<boolean>
task: ComputedRef<TaskItem | null>
canProcess: ComputedRef<boolean>
/** 流程被挂起:待办还在手里,此刻办不动 */
frozen: ComputedRef<boolean>
node: ComputedRef<ActivityNodeBrief | undefined>
/** 这一环的字段权限(hidden / readonly / editable / required) */
fieldPerms: ComputedRef<Record<string, string>>
atBegin: ComputedRef<boolean>
formSchema: ComputedRef<FormSchema | null>
/** 单据数据 + 这条子待办自带的行覆写,两种版式改的是同一份 */
formData: Ref<Record<string, unknown>>
opinion: Ref<string>
/** 改了字段之后标题会不会换一句、换成哪一句 */
titleNext: Ref<string>
/* 外部闸门:写回卡控、OA 按钮锁定、第三方备好的表态 */
writebackBlocked: ComputedRef<boolean>
writebackNote: ComputedRef<string>
oaLockText: ComputedRef<string>
handleLocked: ComputedRef<boolean>
goBackLocked: ComputedRef<boolean>
nodeDecisions: ComputedRef<NodeDecisionView[]>
/* 出口与提交 */
routeButtons: ComputedRef<TaskRouteButton[]>
blockedRoutes: ComputedRef<TaskRouteButton[]>
routeName: Ref<string>
pickRoute: (item: TaskRouteButton) => void
/** 缺哪几格必填没填(口径见 utils/formRuntime) */
requiredMissing: ComputedRef<string[]>
submit: (done?: unknown) => Promise<void>
/* 退回 */
goBackShow: Ref<boolean>
goBackActivity: Ref<string>
goBackWay: Ref<string>
goBackOpinion: Ref<string>
goBackOptions: ComputedRef<{ value: string; label: string }[]>
goBackWayOptions: ComputedRef<{ value: string; label: string }[]>
openGoBack: () => Promise<void>
confirmGoBack: (done?: unknown) => Promise<void>
/* 加签 / 转办 */
peopleShow: Ref<boolean>
peopleMode: Ref<'add' | 'transfer'>
people: Ref<string[]>
peopleOpinion: Ref<string>
addWay: Ref<'before' | 'after'>
addMode: Ref<'together' | 'serial'>
openAddTask: () => void
openTransfer: () => void
confirmPeople: (done?: unknown) => Promise<void>
/* 抄送 / 分享 */
sendShow: Ref<boolean>
sendMode: Ref<'cc' | 'share'>
sendPeople: Ref<string[]>
sendOpinion: Ref<string>
sendRequiresAction: Ref<boolean>
openSend: (mode: 'cc' | 'share') => void
confirmSend: () => Promise<void>
/* 批注 */
comments: Ref<WorkComment[]>
canComment: ComputedRef<boolean>
/** 审批记录开头那一行「谁提交的」:与单据详情页同一个口径(utils/approvalRecord) */
startRecord: ComputedRef<ApprovalStartLike | null>
confirmComment: (payload: RecordCommentPayload) => Promise<void>
removeComment: (id: string) => Promise<void>
/**
* 意见编辑器与批注面板的实例握在这份逻辑手里:提交前要问它贴图传完没有、办完要清草稿。
* 手机版式里那是另一批实例,所以挂载时把它们交回来,别让使用者贴的图静静丢掉。
*/
bindOpinionEditor: (el: unknown) => void
bindRecordPanel: (el: unknown) => void
/* 杂项 */
myIdentity: ComputedRef<string>
reload: () => Promise<void>
confirmDecision: (id: string, done?: unknown) => Promise<void>
rejectDecision: (id: string) => Promise<void>
}
export const TASK_VIEW_KEY: InjectionKey<TaskView> = Symbol('oa-task-view')

View File

@ -0,0 +1,448 @@
// @vitest-environment jsdom
import { beforeAll, describe, expect, it } from 'vitest'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import { fieldText, planForm, readerSections } from './useFormPlan'
import { expenseData, expenseSchema } from './mobileFixtures'
import type { FormFieldDef, FormSchema, MobileLayout } from '@/types'
beforeAll(() => {
// planForm 里的分组名、"已签名" 这几句走的是真词条;测试里不加载就会拿 key 当文案
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
function field(over: Partial<FormFieldDef> & { key: string; type: FormFieldDef['type'] }): FormFieldDef {
return { label: over.key, ...over } as FormFieldDef
}
describe('手机上把表单读成三层', () => {
it('空着的不占一行,但要说折了多少个', () => {
const plan = planForm(expenseSchema(), { data: expenseData() })
const rendered = plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
expect(rendered).not.toContain('empty_note')
expect(plan.dropped).toBeGreaterThan(0)
// 分节标题(分隔条)本身不是一个字段,不进这个数
const dividers = expenseSchema().fields.filter((field) => field.type === 'divider').length
expect(plan.total).toBe(expenseSchema().fields.length - dividers)
})
it('这一环藏起来的格子屏幕上就没有,不进摘要也不占折叠位', () => {
const plan = planForm(expenseSchema(), { data: expenseData(), perms: { secret: 'hidden' } })
const rendered = plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
expect(rendered).not.toContain('secret')
})
it('要人填的那几格归填写块,摘要里不重复出现', () => {
const plan = planForm(expenseSchema(), {
data: expenseData(),
needKeys: ['approved', 'days']
})
const rendered = plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
expect(rendered).not.toContain('approved')
expect(rendered).toContain('reason')
})
it('钱先看到:两个金额上浮,第三个不抢位置', () => {
const schema = {
fields: [
field({ key: 'a', type: 'money' }),
field({ key: 'b', type: 'money' }),
field({ key: 'c', type: 'money' })
]
}
const plan = planForm(schema, { data: { a: 100, b: 200, c: 300 } })
expect(plan.floats.map((item) => item.field.key)).toEqual(['a', 'b'])
const group = plan.groups.flatMap((row) => row.items.map((item) => item.field.key))
expect(group).toContain('c')
})
it('系统取数那几格并成一行,分隔条就是分节标题', () => {
const plan = planForm(expenseSchema(), { data: expenseData() })
expect(plan.auto.map((item) => item.field.key)).toEqual(['serial_no', 'starter', 'starter_no', 'starter_dept', 'leader', 'flow_name'])
// 二、三两节里只剩明细和附件,都被收成别的形式了,就不该留下两节空的
expect(plan.groups.map((group) => group.name)).toEqual(['一、报销基本信息'])
})
it('明细收成一行,条数与合计先说给人听', () => {
const plan = planForm(expenseSchema(), { data: expenseData() })
expect(plan.table?.count).toBe(12)
// 明细里第一个金额列的合计:12 条按五种费用轮着来
// 五条费用轮两遍再补两条:合计要跟明细对得上,手机上那一行说的就是这个数
expect(plan.table?.sum).toBe('7,181.00')
})
it('发票带 id 交给版式摆缩略图,不是只报一个数字', () => {
const plan = planForm(expenseSchema(), { data: expenseData() })
const invoices = plan.media.find((row) => row.field.key === 'invoices')
expect(invoices?.items.map((item) => item.id)).toEqual(['att-1', 'att-2'])
expect(invoices?.items[0].is_image).toBe(true)
expect(invoices?.items[1].is_image).toBe(false)
})
})
describe('把一格的值说成一句人话', () => {
it('选项回显的是名字,不是存的那个码', () => {
const f = field({ key: 'k', type: 'select', options: [{ value: 'a', label: '差旅' }, { value: 'b', label: '招待' }] })
expect(fieldText(f, 'b')).toBe('招待')
const multi = field({ key: 'k', type: 'checkbox', options: [{ value: 'a', label: '差旅' }, { value: 'b', label: '招待' }] })
expect(fieldText(multi, ['a', 'b'])).toBe('差旅、招待')
})
it('金额千分位带单位,开关说是与否', () => {
expect(fieldText(field({ key: 'k', type: 'money', unit: '元' }), 4860)).toBe('4,860.00 元')
expect(fieldText(field({ key: 'k', type: 'switch' }), true)).toBe('是')
expect(fieldText(field({ key: 'k', type: 'switch' }), 0)).toBe('否')
})
it('日期区间连成一段,选人那一格回显名字', () => {
expect(fieldText(field({ key: 'k', type: 'daterange' }), ['2026-11-10', '2026-11-12'])).toBe('2026-11-10 ~ 2026-11-12')
expect(fieldText(field({ key: 'k', type: 'user' }), [{ name: '李明' }])).toBe('李明')
})
it('空值就是一句空话,版式那一侧靠它决定渲不渲染', () => {
expect(fieldText(field({ key: 'k', type: 'text' }), '')).toBe('')
expect(fieldText(field({ key: 'k', type: 'table' }), [])).toBe('')
expect(fieldText(field({ key: 'k', type: 'attachment' }), [])).toBe('')
})
})
/**
* 生产上那张费用报销单的形状:一张「标签页」分两页,第二页整页让给外部系统。
* 手机版式的分节全靠它认,所以这一份照着它建,不用 mobileFixtures 那份纯分隔条的。
*/
function tabsSchema(over: Partial<FormFieldDef>[] = []): { fields: FormFieldDef[] } {
const host = field({
key: 'tabs_host',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '费用报销基本信息' },
{ key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }
],
tabsMode: 'collapse'
})
return {
fields: [
host,
field({ key: 'reason', type: 'textarea', tab: 'tab_1' }),
field({ key: 'city', type: 'text', tab: 'tab_1' }),
field({ key: 'invoice_no', type: 'text', tab: 'tab_2' }),
...over
]
}
}
describe('页签与「手机上不展示」这两档', () => {
it('勾了手机上不展示的那一格,摘要里哪儿都不出现,而且单独计个数', () => {
const schema = {
fields: [field({ key: 'a', type: 'text' }), field({ key: 'b', type: 'text', mobileHidden: true }), field({ key: 'c', type: 'text' })]
}
const plan = planForm(schema, { data: { a: '甲', b: '乙', c: '丙' } })
const rendered = plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
expect(rendered).toEqual(['a', 'c'])
// 它不是"因为空着被折起来",所以不该混进 dropped,否则那句"折了多少个空的"就成了假话
expect(plan.hiddenMobile).toBe(1)
expect(plan.dropped).toBe(0)
expect(plan.total).toBe(3)
})
it('分节名先认页签,分隔条是页里的第二段', () => {
const plan = planForm(tabsSchema(), { data: { reason: '出差', city: '北京', invoice_no: 'FP-1' } })
expect(plan.groups.map((group) => group.name)).toEqual(['费用报销基本信息'])
expect(plan.groups[0].items.map((item) => item.field.key)).toEqual(['reason', 'city'])
})
it('页签里再打分隔条时段名两段都写,跨页时上一页那条不跟过去', () => {
const schema = {
fields: [
field({ key: 'tabs_host', type: 'tabs', tabs: [{ key: 'tab_1', label: '费用报销基本信息' }, { key: 'tab_2', label: '发票信息', kind: 'embed' }] }),
field({ key: 'sec_one', label: '第一段', type: 'divider', tab: 'tab_1' }),
field({ key: 'reason', type: 'textarea', tab: 'tab_1' }),
field({ key: 'city', type: 'text', tab: 'tab_1' }),
field({ key: 'sec_two', label: '第二段', type: 'divider', tab: 'tab_1' }),
field({ key: 'late', type: 'text', tab: 'tab_1' }),
// 第二页上没写分隔条:第一页那条"第二段"不该跟过来
field({ key: 'other', type: 'text', tab: 'tab_2' })
]
}
const plan = planForm(schema, { data: { reason: '出差', city: '北京', late: '补', other: '不该出现' } })
expect(plan.groups.map((group) => group.name)).toEqual(['费用报销基本信息 · 第一段', '费用报销基本信息 · 第二段'])
expect(plan.groups[1].items.map((item) => item.field.key)).toEqual(['late'])
})
it('压在外部页面那一页上的格子不摆,也不谎称是空的', () => {
const plan = planForm(tabsSchema(), { data: { reason: '出差', city: '北京', invoice_no: 'FP-1' } })
const rendered = plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
expect(rendered).not.toContain('invoice_no')
expect(plan.dropped).toBe(1)
})
})
describe('完整单据那一屏的读法', () => {
it('按页签分节,外部页面那一节只给一张卡片', () => {
const plan = readerSections(tabsSchema(), { data: { reason: '出差', city: '', invoice_no: 'FP-1' } })
expect(plan.sections.map((row) => row.name)).toEqual(['费用报销基本信息', '费用报销发票信息'])
const form = plan.sections[0]
const embed = plan.sections[1]
expect(form.rows.map((row) => row.field.key)).toEqual(['reason', 'city'])
expect(embed.embed).toBe(true)
expect(embed.rows).toEqual([])
// 那一格的 key 必须还是标签页容器自己的:后端发免登地址前按它重算可见性
expect(embed.embedField?.key).toBe('tabs_host')
expect(embed.embedField?.type).toBe('embed')
})
it('空着的一格照样留一行:看得出这张单少填了什么', () => {
const plan = readerSections(tabsSchema(), { data: { reason: '出差' } })
const city = plan.sections[0].rows.find((row) => row.field.key === 'city')
expect(city?.empty).toBe(true)
expect(city?.text).toBe('')
})
it('手机上不展示的格子在这屏也不出现,单独报数;环节藏起来的另算一笔', () => {
const schema = tabsSchema([field({ key: 'gone', type: 'text', tab: 'tab_1', mobileHidden: true })])
const plan = readerSections(schema, { data: { reason: '出差', city: '北京', gone: '不摆' }, perms: { city: 'hidden' } })
const keys = plan.sections.flatMap((row) => row.rows.map((item) => item.field.key))
expect(keys).toEqual(['reason'])
expect(plan.hidden).toBe(1)
expect(plan.dropped).toBe(2) // city 被环节藏了 + invoice_no 压在外部页面那一页
})
it('没有页签时照旧按分隔条分节,抬头那几格系统取数自己一节,空值行也留着', () => {
const plan = readerSections(expenseSchema(), { data: expenseData() })
expect(plan.sections.map((row) => row.name)).toEqual(['系统取数', '一、报销基本信息', '二、费用明细', '三、票据'])
expect(plan.sections[0].rows.map((row) => row.field.key)).toEqual(['serial_no', 'starter', 'starter_no', 'starter_dept', 'leader', 'flow_name'])
const base = plan.sections[1]
expect(base.rows.map((row) => row.field.key)).toContain('empty_note')
expect(base.rows.find((row) => row.field.key === 'empty_note')?.empty).toBe(true)
})
it('附件、明细、签名各归各的读法', () => {
const plan = readerSections(expenseSchema(), { data: expenseData() })
const bill = plan.sections.find((row) => row.name === '三、票据')
expect(bill?.rows.find((row) => row.field.key === 'invoices')?.kind).toBe('media')
expect(bill?.rows.find((row) => row.field.key === 'signed')?.kind).toBe('signature')
const detail = plan.sections.find((row) => row.name === '二、费用明细')
const table = detail?.rows.find((row) => row.field.key === 'rows')
expect(table?.kind).toBe('table')
expect(table?.rows.length).toBe(12)
})
})
/**
* 配了「手机端」面板那一档之后:手机上只出一节,摆哪几格、什么顺序、每格怎么摆照配置。
* 上面那一大段盯的是没配过的表单——那些用例一个字没动,正是这一档不该碰的东西。
*/
describe('按配置摆的那一版:只有一节', () => {
function mobileSchema(mobile: MobileLayout, fields = expenseSchema().fields): FormSchema {
return { fields, layout: { columns: 12, grid: 12, mobile } }
}
const keys = (plan: ReturnType<typeof planForm>) => plan.groups.flatMap((group) => group.items.map((item) => item.field.key))
/** 只讲顺序与闸门的那几张表:别拉上四十几格的报销单,读用例的人只看那五六格。 */
const TINY: FormFieldDef[] = [
field({ key: 'reason', label: '报销事由', type: 'textarea' }),
field({ key: 'city', label: '目的地', type: 'text' }),
field({ key: 'amount', label: '报销金额', type: 'money' }),
field({ key: 'approved', label: '核准金额', type: 'money' }),
field({ key: 'days', label: '出差天数', type: 'number' }),
field({ key: 'empty_note', label: '备注', type: 'text' }),
field({ key: 'secret', label: '内部编号', type: 'text', mobileHidden: true })
]
const TINY_DATA = { reason: '出差', city: '北京', amount: 4860, approved: 4800, days: 3, empty_note: '', secret: '已作废' }
it('没配过的表单不走这一版,配了才走', () => {
expect(planForm(expenseSchema(), { data: expenseData() }).custom).toBe(false)
expect(planForm(mobileSchema({ enabled: false }, TINY), { data: TINY_DATA }).custom).toBe(false)
expect(planForm(mobileSchema({ enabled: true }, TINY), { data: TINY_DATA }).custom).toBe(true)
})
it('只出一节:节名照配置,系统取数不再并走,明细与附件跟着格子摆进这一节', () => {
const plan = planForm(
mobileSchema({
enabled: true,
title: '费用报销基本信息',
fields: [
{ key: 'starter_dept' },
{ key: 'reason', style: 'block' },
{ key: 'amount' },
{ key: 'rows', style: 'list' },
{ key: 'invoices' }
]
}),
{ data: expenseData() }
)
expect(plan.groups.map((group) => group.name)).toEqual(['费用报销基本信息'])
expect(keys(plan)).toEqual(['starter_dept', 'reason', 'amount', 'rows', 'invoices', 'serial_no', 'starter', 'starter_no', 'leader', 'flow_name', 'approved', 'days', 'trip', 'city', 'empty_note', 'secret', 'contracts', 'signed'])
// 系统取数不再另起一行「系统取数 N 项」:配了它,它就是这一节里的一格
expect(plan.auto).toEqual([])
expect(plan.media).toEqual([])
expect(plan.groups[0].items[0].field.type).toBe('auto')
expect(plan.groups[0].items[0].text).toBe('软件开发事业部')
expect(plan.groups[0].items[1].style).toBe('block')
// 明细挑了「逐条展开」:行跟着这一格走,不再另填 plan.table 那一桶
expect(plan.groups[0].items[3].kind).toBe('table')
expect(plan.groups[0].items[3].rows).toHaveLength(12)
expect(plan.table).toBeNull()
// 附件跟着格子的位置摆在这一节里
expect(plan.groups[0].items[4].kind).toBe('media')
expect(plan.groups[0].items[4].items.length).toBeGreaterThan(0)
})
it('配了却没写到的格子补在后面,不会因为没人配过就凭空消失', () => {
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'city' }] }, TINY), { data: TINY_DATA })
expect(keys(plan)).toEqual(['city', 'reason', 'amount', 'approved', 'days', 'empty_note'])
})
it('点名要的格子空着也摆:不能因为没值就自己消失', () => {
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'empty_note' }, { key: 'city' }] }, TINY), { data: TINY_DATA })
const row = plan.groups[0].items[0]
expect(row.field.key).toBe('empty_note')
expect(row.text).toBe('')
})
it('环节权限、手机上不展示两道闸一道没少', () => {
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }, { key: 'city' }, { key: 'secret' }] }, TINY), {
data: TINY_DATA,
perms: { city: 'hidden' }
})
expect(keys(plan)).toEqual(['reason', 'amount', 'approved', 'days', 'empty_note'])
expect(plan.dropped).toBe(1)
expect(plan.hiddenMobile).toBe(1)
})
it('整张流程「默认隐藏」的格子在这儿也一样不摆', () => {
const fields = [...TINY, field({ key: 'quiet', label: '内部字段', type: 'text', hidden: true })]
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'quiet' }, { key: 'city' }] }, fields), { data: { ...TINY_DATA, quiet: 'X' } })
expect(keys(plan)).not.toContain('quiet')
expect(plan.dropped).toBe(1)
})
it('要人填的那几格归上面的填写块,这一节里不重复摆', () => {
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }, { key: 'approved' }] }, TINY), {
data: TINY_DATA,
needKeys: ['approved']
})
expect(keys(plan)).not.toContain('approved')
expect(keys(plan)).toContain('reason')
})
it('「置顶」的格子进抬头那排大字,最多三格', () => {
const plan = planForm(
mobileSchema(
{
enabled: true,
fields: [
{ key: 'amount', style: 'float' },
{ key: 'approved', style: 'float' },
{ key: 'reason' }
]
},
TINY
),
{ data: TINY_DATA }
)
expect(plan.floats.map((item) => item.field.key)).toEqual(['amount', 'approved'])
expect(keys(plan)).not.toContain('amount')
})
it('配了「置顶」的格子超出三格时,多出来的回到这一节里,不丢', () => {
const fields = [
field({ key: 'm1', label: '一', type: 'money' }),
field({ key: 'm2', label: '二', type: 'money' }),
field({ key: 'm3', label: '三', type: 'money' }),
field({ key: 'm4', label: '四', type: 'money' })
]
const plan = planForm(
mobileSchema(
{
enabled: true,
fields: [
{ key: 'm1', style: 'float' },
{ key: 'm2', style: 'float' },
{ key: 'm3', style: 'float' },
{ key: 'm4', style: 'float' }
]
},
fields
),
{ data: { m1: 1, m2: 2, m3: 3, m4: 4 } }
)
expect(plan.floats.map((item) => item.field.key)).toEqual(['m1', 'm2', 'm3'])
expect(keys(plan)).toEqual(['m4'])
})
it('节名没配就取第一个页签的名字;既没配也没页签才写「表单内容」', () => {
const withTabs = [field({ key: 'tabs_host', type: 'tabs', tabs: [{ key: 'tab_1', label: '费用报销基本信息' }] }), field({ key: 'reason', type: 'textarea', tab: 'tab_1' })]
expect(planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, withTabs), { data: { reason: '出差' } }).groups[0]?.name).toBe('费用报销基本信息')
// 外部页面那一页不作数:那一页在手机上是一张卡片,不是这一节的正文
const embedFirst = [
field({ key: 'tabs_host', type: 'tabs', tabs: [{ key: 'tab_e', label: 'ERP 单据', kind: 'embed' }, { key: 'tab_1', label: '费用报销基本信息' }] }),
field({ key: 'reason', type: 'textarea', tab: 'tab_1' })
]
expect(planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, embedFirst), { data: { reason: '出差' } }).groups[0]?.name).toBe('费用报销基本信息')
expect(planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, TINY), { data: TINY_DATA }).groups[0]?.name).toBe('表单内容')
})
it('明细收成一行时照样填 plan.table:明细那一屏与几处判据读的都是它', () => {
const plan = planForm(mobileSchema({ enabled: true, fields: [{ key: 'rows', style: 'card' }] }), { data: expenseData() })
expect(plan.table?.count).toBe(12)
expect(plan.table?.sum).toBe('7,181.00')
expect(plan.groups[0].items[0].text).toBe('12 条')
expect(plan.groups[0].items[0].style).toBe('card')
})
it('「完整单据」入口配了不要就没有', () => {
expect(planForm(mobileSchema({ enabled: true }, TINY), { data: TINY_DATA }).showFull).toBe(false)
expect(planForm(mobileSchema({ enabled: true, showFullSheet: true }, TINY), { data: TINY_DATA }).showFull).toBe(true)
// 没配这一档的老表单永远留着这一入口,与从前一模一样
expect(planForm(expenseSchema(), { data: expenseData() }).showFull).toBe(true)
})
/** 生产那张单的形状:一张「标签页」两页,第二页整页是别人的系统。 */
const TABED: FormFieldDef[] = [
field({
key: 'tabs_host',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '费用报销基本信息' },
{ key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }
]
}),
field({ key: 'reason', label: '报销事由', type: 'textarea', tab: 'tab_1' }),
field({ key: 'invoice_no', label: '发票号', type: 'text', tab: 'tab_2' })
]
const TABED_DATA = { reason: '出差', invoice_no: 'FP-1' }
it('外部页面那一页也进这一节:一张「打开」卡片,名字取页签名', () => {
const items = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, TABED), { data: TABED_DATA }).groups[0].items
// 压在外部页面那一页上的格子照样能摆:那一页在手机上不内嵌,那几个值总得有个地方看
expect(items.map((row) => row.field.key)).toEqual(['reason', 'invoice_no', 'tabs_host'])
const embed = items[2]
expect(embed.kind).toBe('embed')
expect(embed.style).toBe('embed')
expect(embed.label).toBe('费用报销发票信息')
expect(embed.slotKey).toBe('tabs_host#tab_2')
// 那一整页没有"值"可念成一句话
expect(embed.text).toBe('')
})
it('那一页能单独勾掉;环节藏掉整片或只藏那一页,都不摆', () => {
const offByConfig = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }, { key: 'tabs_host#tab_2', hidden: true }] }, TABED), { data: TABED_DATA })
expect(offByConfig.groups[0].items.map((row) => row.kind)).not.toContain('embed')
expect(offByConfig.hiddenMobile).toBe(1)
const offByHost = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, TABED), { data: TABED_DATA, perms: { tabs_host: 'hidden' } })
expect(offByHost.groups[0].items.map((row) => row.kind)).not.toContain('embed')
expect(offByHost.dropped).toBeGreaterThan(0)
// 只藏那一页:记在 formPerms 里那个 `标签页格子key#页签key`
const offByPage = planForm(mobileSchema({ enabled: true, fields: [{ key: 'reason' }] }, TABED), { data: TABED_DATA, perms: { 'tabs_host#tab_2': 'hidden' } })
expect(offByPage.groups[0].items.map((row) => row.kind)).not.toContain('embed')
})
it('自动归置那一版不碰这一页:没配手机端版式的表单一个像素都不变', () => {
const plan = planForm({ fields: TABED }, { data: TABED_DATA })
expect(plan.custom).toBe(false)
expect(plan.groups.flatMap((group) => group.items.map((item) => item.kind))).not.toContain('embed')
})
})

View File

@ -0,0 +1,597 @@
/**
* 手机上怎么把一张桌面 12 列的表单讲清楚:不照抄网格,按「判断这件事需要看什么」分三层。
*
* 桌面一行四列摊得开,手机上塌成单列就是一屏放不下一行、四十七个字段滚六屏。
* 这一层把字段按现成的类型重新归置,不新增任何配置:
*
* 空值 不渲染(看不见的东西不该占一行)
* money 最多两条上浮到摘要头,先让人看到钱
* auto 合并成一行「系统取数」,折叠——发起人是谁、哪个部门,抬头已经有了
* table 收成一行「明细 N 条 · 合计 X」,点开才是逐条
* attachment/image 缩略图横滑,不占字段行
* divider 天然的分节标题,默认收起
* signature 只在完整单据里看
*
* 只读文本的口径也在这里出,手机上不渲染控件;要改值走「完整单据」或本环节的填写块。
*/
import { i18n } from '@/i18n'
import { MOBILE_FLOAT_MAX, mobileEntries, mobileFieldLabel, mobileLayoutOf, styleFor } from '@/utils/mobileLayout'
import { personText } from '@/utils/personLabel'
import { isEmbedTab, isTabsField, tabEmbedField, tabKeyOf, tabsFieldOf, tabsOf } from '@/utils/tabPages'
import type { AttachmentItem, FormFieldDef, FormSchema, FormTabDef, MobileFieldLayout, MobileFieldStyle, MobileLayout } from '@/types'
export interface PlanItem {
field: FormFieldDef
text: string
/** 手机上这一格抬头写的名字:配了短名用短名,否则就是字段标题 */
label: string
/** 长文本(事由、说明)单独占一块,不跟标签挤同一行 */
long: boolean
numeric: boolean
/**
* 这一格是什么料:文本 / 附件 / 明细 / 签名。自动归置那一版把 media 与 table
* 拣出去单独摆,用不上它;「按配置摆」那一版所有格子排进同一节,摆法得跟着格子走。
*/
kind: 'text' | 'media' | 'table' | 'signature' | 'embed'
/** 这一格按哪一档摆法上屏(口径见 utils/mobileLayout.ts) */
style: MobileFieldStyle
/** kind=embed:那一页外部页面的回写分区键(`标签页格子key#页签key`),普通格子为空 */
slotKey: string
/** kind=media:直接交给画廊的那一份 */
items: AttachmentItem[]
/** kind=table:摆法是「逐条展开」时要摊开的那些行 */
rows: Record<string, unknown>[]
}
export interface PlanGroup {
name: string
items: PlanItem[]
}
export interface PlanMedia {
field: FormFieldDef
/** 直接交给 AttachmentGallery 的那一份:id 在,缩略图就取到字节 */
items: AttachmentItem[]
}
export interface FormPlan {
floats: PlanItem[]
groups: PlanGroup[]
auto: PlanItem[]
media: PlanMedia[]
table: { field: FormFieldDef; count: number; sum: string } | null
signature: PlanItem | null
/** 因为空值或环节权限没渲染的字段数:给「完整单据」那行说清楚折叠了多少 */
dropped: number
/** 被表单自己勾了「手机上不展示」的格子数:那一格在手机上哪儿都不出现 */
hiddenMobile: number
total: number
/**
* 这一份计划是按表单上的手机端配置摆出来的(`layout.mobile.enabled`)。
* true 时只有一节,`auto` / `media` / `signature` 那三个单独摆的桶一律是空的——
* 内容全按配置挤进 `groups[0]` 里按顺序摆,摆法看每格的 `style`。
*/
custom: boolean
/** 末尾要不要留「完整单据」那一屏:配置里说不要就没有(不要就是不要) */
showFull: boolean
}
/** 「完整单据」那一屏的一行:一格一行,空值也留着(看得出这张单少填了什么)。 */
export interface ReaderRow {
field: FormFieldDef
text: string
empty: boolean
kind: 'text' | 'media' | 'table' | 'signature'
items: AttachmentItem[]
rows: Record<string, unknown>[]
}
/** 一节:一个页签(或一条分隔条)管的那几格;embed 那一页只有卡片,没有格子。 */
export interface ReaderSection {
key: string
name: string
rows: ReaderRow[]
embedField: FormFieldDef | null
/** 这一节是外部系统的页面:手机上不内嵌,给一张「打开」卡片 */
embed: boolean
}
export interface ReaderPlan {
sections: ReaderSection[]
/** 手机上不展示的格子数:设计器里逐格勾的那一档,要说给配表的人听 */
hidden: number
/** 这一屏没摆但是有原因的格子数:环节权限藏起来、整单默认隐藏、压在外部页面那一页上 */
dropped: number
total: number
}
const NUMERIC = new Set(['money', 'number', 'formula', 'rate'])
const MEDIA = new Set(['attachment', 'image'])
/**
* 明细那一条摆哪几列、各摆成什么话:只摆填了的那几列,空列不占行。
*
* 「完整单据」那一屏与「按配置摆」的摘要都要摊明细,判据得是同一份,
* 不然同一张单在两处能读出不一样的列。
*/
export function mobileRowCells(field: FormFieldDef, item: Record<string, unknown>) {
const columns = (field.columns ?? []).filter((col) => !['divider', 'description', 'title'].includes(String(col.type)))
const row = item ?? {}
return columns
.map((col) => ({
key: String(col.key),
label: String(col.label ?? col.key),
value: String(row[col.key] ?? '').trim(),
numeric: NUMERIC.has(String(col.type))
}))
.filter((cell) => cell.value !== '')
}
function t(key: string, params?: Record<string, unknown>) {
return params ? i18n.global.t(key, params) : i18n.global.t(key)
}
function isEmpty(value: unknown): boolean {
if (value === null || value === undefined) return true
if (typeof value === 'string') return value.trim() === ''
if (Array.isArray(value)) return value.length === 0
if (typeof value === 'object') return Object.keys(value as object).length === 0
return false
}
function optionLabel(field: FormFieldDef, value: unknown): string {
const list = field.options ?? []
const hit = list.find((item) => String(item.value) === String(value))
return hit ? String(hit.label ?? hit.value) : String(value)
}
function money(value: unknown): string {
const num = Number(value)
if (!Number.isFinite(num)) return String(value)
return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
/** 一条明细里第一个金额列的合计:没有金额列就不显示合计,不硬凑。 */
function rowsSum(rows: Record<string, unknown>[], columns: FormFieldDef[] = []): string {
const moneyCol = columns.find((col) => col.type === 'money' || col.type === 'number')
if (!moneyCol) return ''
const sum = rows.reduce((acc, row) => acc + (Number(row?.[moneyCol.key]) || 0), 0)
return money(sum)
}
/**
* 表单里那一格附件收成画廊认得的那份。
*
* 发票、合同扫描件就住在这几格里:手机上把它们缩成一行「附件 3」,等于把一单报销最该看的
* 东西藏起来了,所以这一份要带着 id 往下走,让版式能直接摆缩略图。
*/
function filesOf(value: unknown): AttachmentItem[] {
if (!Array.isArray(value)) return []
return value
.filter((item) => item && typeof item === 'object')
.map((item) => {
const row = item as Record<string, unknown>
const raw = String(row.name || row.file_name || row.url || '')
const ext = String(row.extension || '').toLowerCase()
const kind = String(row.type || '')
return {
id: String(row.id ?? raw),
name: raw.split('/').pop() || t('task.attachments'),
extension: ext,
length: Number(row.length ?? row.size ?? 0) || 0,
is_image: /^image\//.test(kind) || ['png', 'jpg', 'jpeg', 'gif', 'webp', 'heic'].includes(ext),
...(row.download_url ? { download_url: String(row.download_url) } : {}),
...(row.preview_url ? { preview_url: String(row.preview_url) } : {})
} as AttachmentItem
})
}
/** 把一格的值说成一句人话。控件不渲染,所以这一句就是手机上看到的全部内容。 */
export function fieldText(field: FormFieldDef, value: unknown): string {
if (isEmpty(value)) return ''
if (field.type === 'switch') return value === true || value === 'true' || value === 1 ? t('common.yes') : t('common.no')
if (MEDIA.has(field.type)) return String(filesOf(value).length)
if (field.type === 'table') return String(Array.isArray(value) ? value.length : 0)
if (field.type === 'signature') return t('mobile.signed')
if (field.type === 'money') return `${money(value)}${field.unit ? ` ${field.unit}` : ''}`
if (NUMERIC.has(field.type)) {
const num = Number(value)
const text = Number.isFinite(num) ? String(value) : String(value)
return field.unit ? `${text} ${field.unit}` : text
}
if (['select', 'radio', 'picker', 'cascader'].includes(field.type)) {
return Array.isArray(value) ? value.map((item) => optionLabel(field, item)).join('、') : optionLabel(field, value)
}
if (field.type === 'checkbox') {
const list = Array.isArray(value) ? value : [value]
return list.map((item) => optionLabel(field, item)).join('、')
}
if (['user', 'dept'].includes(field.type)) {
const list = Array.isArray(value) ? value : [value]
return list.map((item) => (typeof item === 'string' ? personText(item) : String((item as Record<string, unknown>)?.name ?? item))).join('、')
}
if (field.type === 'relation') {
const list = Array.isArray(value) ? value : [value]
return list.map((item) => String((item as Record<string, unknown>)?.title ?? (item as Record<string, unknown>)?.serial ?? item)).join('、')
}
if (field.type === 'daterange' || field.type === 'timerange') {
const list = Array.isArray(value) ? value : [value]
return list.filter((item) => !isEmpty(item)).join(' ~ ')
}
if (typeof value === 'object') {
const row = value as Record<string, unknown>
return String(row.title ?? row.name ?? row.label ?? row.text ?? '')
}
return String(value)
}
export interface PlanOptions {
data: Record<string, unknown>
/** 环节字段权限:hidden 的格子屏幕上就没有,不该占位,也不该进折叠分组 */
perms?: Record<string, string>
/** 本环节要人填的字段:由详情页顶部的填写块负责,摘要里不重复出现 */
needKeys?: string[]
/** 只读展示(已办、抄送、归档件):填写块由调用方自己决定渲不渲染 */
readonly?: boolean
}
export function planForm(schema: FormSchema | null | undefined, options: PlanOptions): FormPlan {
const fields = schema?.fields ?? []
const { data, perms = {}, needKeys = [] } = options
const need = new Set(needKeys)
const plan: FormPlan = {
floats: [],
groups: [],
auto: [],
media: [],
table: null,
signature: null,
dropped: 0,
hiddenMobile: 0,
total: 0,
custom: false,
showFull: true
}
// 配了手机端版式就换一条路走:只出一节,摆哪些格、什么顺序、每格怎么摆全看配置。
// 没配(老表单全是这样)连这个函数都不进,下面那套自动归置一个字都不动。
const mobile = mobileLayoutOf(schema)
if (mobile) return planByMobileLayout(mobile)
const pages = pageListOf(fields)
let group: PlanGroup | null = null
let divider = ''
let atTab = ''
const pushGroup = (name: string) => {
const found = plan.groups.find((item) => item.name === name)
if (found) return found
const created: PlanGroup = { name, items: [] }
plan.groups.push(created)
return created
}
for (const field of fields) {
if (isLayoutField(field)) continue
// 换到另一页时,上一页那条分隔条不跟过去:它是那一页里的分段
const at = String(pageOf(field, pages)?.key ?? '')
if (at !== atTab) {
atTab = at
divider = ''
group = null
}
if (field.type === 'divider') {
divider = String(field.label || field.key || '')
group = pushGroup(sectionName(field, pages, divider))
continue
}
plan.total += 1
// 环节权限与「默认隐藏」之外还有一档:设计器上勾了「手机上不展示」的那一格,
// 手机上摘要与完整单据都不摆,电脑上照旧。它不是被折叠,所以不进 dropped。
if (field.mobileHidden) {
plan.hiddenMobile += 1
continue
}
if (perms[field.key] === 'hidden' || field.hidden) {
plan.dropped += 1
continue
}
// 落在外部页面那一页上的格子不摆(那张页面归「完整单据」那一屏),也不重复计空值
if (onEmbedPage(field, pages)) {
plan.dropped += 1
continue
}
const value = data?.[field.key]
if (need.has(field.key)) continue
if (isEmpty(value)) {
// 附件类空值就是「没附件」,不必再占一行说它为空
plan.dropped += 1
continue
}
if (field.type === 'auto') {
plan.auto.push(item(field, value))
continue
}
if (MEDIA.has(field.type)) {
const files = filesOf(value)
if (files.length) plan.media.push({ field, items: files })
else plan.dropped += 1
continue
}
if (field.type === 'table') {
const rows = Array.isArray(value) ? (value as Record<string, unknown>[]) : []
plan.table = { field, count: rows.length, sum: rowsSum(rows, field.columns) }
continue
}
if (field.type === 'signature') {
plan.signature = item(field, value)
continue
}
if (field.type === 'money' && plan.floats.length < 2) {
plan.floats.push(item(field, value))
continue
}
group = pushGroup(sectionName(field, pages, divider))
group.items.push(item(field, value))
}
plan.groups = plan.groups.filter((row) => row.items.length)
return plan
function item(field: FormFieldDef, value: unknown, entry?: MobileFieldLayout): PlanItem {
const text = fieldText(field, value)
const long = text.length > 44 || field.type === 'textarea' || field.type === 'richtext'
return {
field,
label: mobileFieldLabel(field, mobile, entry),
text,
long,
numeric: NUMERIC.has(field.type),
kind: kindOf(field),
style: mobile && entry ? styleFor(field, mobile, entry) : long ? 'block' : 'row',
slotKey: '',
items: [],
rows: []
}
}
/**
* 按配置摆的那一版:一节,节名、格子顺序、每格摆法都在配置里说。
*
* 与自动归置那版三处不一样,都是照着「我就要一节」这句话来的:
*
* - 系统取数不再并成一行「系统取数 N 项」——配了它,它就是一格,跟别的格平起平坐;
* - 空值照样摆(右边一个 `—`):配表的人点名要的格子,不能因为没值就自己消失;
* - 明细、附件、签名跟着各自的位置摆进这一节,不再各归各的桶。
*
* 闸门一道没少:环节权限 `hidden`、整单「默认隐藏」、逐格「手机上不展示」、
* 以及本环节要人填的那几格(上面有填写块),仍然一律不上这一屏。
*/
function planByMobileLayout(config: MobileLayout): FormPlan {
const section: PlanGroup = { name: String(config.title ?? '').trim() || mobileSectionName(fields), items: [] }
plan.custom = true
plan.showFull = Boolean(config.showFullSheet)
for (const { field, entry, embed, slotKey } of mobileEntries(config, fields)) {
plan.total += 1
// 外部页面那一格不是格子,身上没地方挂「手机上不展示」,那颗开关存在配置的 hidden 上
if (embed ? entry.hidden : field.mobileHidden) {
plan.hiddenMobile += 1
continue
}
// 环节权限两档都算数:藏掉整个「标签页」那一格,或者只藏掉外部页面那一页(slotKey 那一档)
if (perms[field.key] === 'hidden' || (slotKey && perms[slotKey] === 'hidden') || field.hidden) {
plan.dropped += 1
continue
}
if (need.has(field.key)) continue
const value = data?.[field.key]
const row = item(field, value, entry)
if (embed) {
// 那一整页是别人系统里的东西,没有"值"可念成一句话;给一张「打开」卡片,点了新窗口看,
// 与「完整单据」那一屏同一口径(390px 里嵌一整张 ERP 表等于没法看)
row.text = ''
row.long = false
row.slotKey = slotKey
}
// 置顶那几格住的是抬头那一排大字,不住在这一节里;超出上限的收回节内,不丢
if (row.style === 'float' && plan.floats.length < MOBILE_FLOAT_MAX) {
plan.floats.push(row)
continue
}
if (row.kind === 'table') {
row.rows = Array.isArray(value) ? (value as Record<string, unknown>[]) : []
row.text = t('mobile.rowsCount', { count: row.rows.length })
// 摆法是「收成一行」时照样填一份 plan.table:明细那一屏和几处判据读的是它,不另起炉灶
if (row.style !== 'list' && !plan.table) plan.table = { field, count: row.rows.length, sum: rowsSum(row.rows, field.columns) }
}
if (row.kind === 'media') {
row.items = filesOf(value)
row.text = String(row.items.length)
}
// 签名存的就是那张图:跟「完整单据」那一屏一样把原值交下去,版式自己画
if (row.kind === 'signature') row.text = isEmpty(value) ? '' : String(value)
section.items.push(row)
}
if (section.items.length) plan.groups.push(section)
return plan
}
}
/** 这一格是什么料:版式照着它决定摆缩略图、摊明细还是把签名那张图画出来。 */
function kindOf(field: FormFieldDef): PlanItem['kind'] {
if (field.type === 'embed') return 'embed'
if (MEDIA.has(field.type)) return 'media'
if (field.type === 'table') return 'table'
if (field.type === 'signature') return 'signature'
return 'text'
}
/**
* 配置没写节名时的兜底:有页签就取第一个页签的名字——配表的人既然把这张单分成了
* 「基本信息 / 票据」两页,手机上要的那一节多半就是第一页;再没有就叫「表单内容」。
*/
function mobileSectionName(fields: FormFieldDef[]): string {
const pages = pageListOf(fields)
const first = pages.find((tab) => !isEmbedTab(tab)) ?? pages[0]
return String(first?.label ?? '').trim() || t('work.formData')
}
/** 排版件:自己不摆值。divider 不在这里——它下面要当分节标题用。 */
function isLayoutField(field: FormFieldDef): boolean {
return isTabsField(field) || field.type === 'title' || field.type === 'description'
}
/** 这张表单上的那几页;没摆「标签页」这一格时回空数组,一切照旧。 */
function pageListOf(fields: FormFieldDef[]): FormTabDef[] {
const host = tabsFieldOf(fields)
return host ? tabsOf(host) : []
}
/** 这一格落在哪一页;没有标签页回 null。 */
function pageOf(field: FormFieldDef, pages: FormTabDef[]): FormTabDef | null {
if (!pages.length) return null
return pages.find((tab) => tab.key === tabKeyOf(field, pages)) ?? null
}
/** 这一页是外部系统那一页:压在它上面的格子在屏幕上根本显示不出来。 */
function onEmbedPage(field: FormFieldDef, pages: FormTabDef[]): boolean {
return isEmbedTab(pageOf(field, pages))
}
/**
* 一节的名字:页签名在前,分隔条在后。
*
* 为什么页签优先:配表的人把一张单分成「基本信息 / 发票信息」两页,手机上第一眼就该
* 看见这两个词;分隔条是某一页里面的分段,比页签低一层。
*/
function sectionName(field: FormFieldDef, pages: FormTabDef[], divider: string): string {
const tab = String(pageOf(field, pages)?.label ?? '').trim()
const head = [tab, String(divider ?? '').trim()].filter(Boolean).join(' · ')
return head || t('work.formData')
}
/**
* 「完整单据」那一屏的分节名,比摘要多一档兜底:既没分页也没分隔条的表,
* 抬头连着那几格系统取数(单号、发起人、部门…)归进「系统取数」一节。
*
* 不然它们会挤进一个叫「表单内容」的节里——那三个字什么也没说,而摘要那一屏
* 早就把这六格并成同一句话了,两处对不上号更难读。
*/
function readerSectionName(field: FormFieldDef, page: FormTabDef | null, divider: string): string {
const head = [String(page?.label ?? '').trim(), String(divider ?? '').trim()].filter(Boolean).join(' · ')
if (head) return head
return field.type === 'auto' ? t('mobile.autoFields') : t('work.formData')
}
export interface ReaderOptions {
data: Record<string, unknown>
/** 环节字段权限(要用 expandPerms 展开过页签那一档):hidden 的格子上不了屏 */
perms?: Record<string, string>
}
/**
* 「完整单据」那一屏的读法:一格一行、按页签与分隔条分节、空值也留着。
*
* 为什么不让手机上直接复用桌面那套只读渲染:FormRenderer 的分节与列宽全是按桌面 12 列
* 网格的行号算的,390px 宽每格独占一行时行号全错配——段头会一起堆到最顶上,页签更是
* 整个塌掉。这一份把「有哪几页、哪一格在哪一页」自己认一遍,出来就是手机上读得顺的
* 那份顺序,与后端、与桌面用的是同一套 tabPages 口径。
*/
export function readerSections(schema: FormSchema | null | undefined, options: ReaderOptions): ReaderPlan {
const fields = schema?.fields ?? []
const { data, perms = {} } = options
const pages = pageListOf(fields)
const host = tabsFieldOf(fields)
const plan: ReaderPlan = { sections: [], hidden: 0, dropped: 0, total: 0 }
let divider = ''
/** 外部页面那一页:手机上不内嵌,只摆一张「打开」卡片,所以这一节没有格子 */
const pushEmbedSection = (tab: FormTabDef) => {
plan.sections.push({
key: `embed:${tab.key}`,
name: String(tab.label ?? '').trim() || t('work.formData'),
rows: [],
embedField: host ? tabEmbedField(host, tab) : null,
embed: true
})
}
const sectionFor = (field: FormFieldDef, page: FormTabDef | null) => {
const name = readerSectionName(field, page, divider)
const found = plan.sections.find((row) => !row.embed && row.name === name)
if (found) return found
const created: ReaderSection = { key: name, name, rows: [], embedField: null, embed: false }
plan.sections.push(created)
return created
}
const walk = (list: FormFieldDef[], page: FormTabDef | null) => {
divider = ''
for (const field of list) {
if (isLayoutField(field) || isTabsField(field)) continue
if (field.type === 'divider') {
divider = String(field.label || field.key || '')
// 段头先占住这一节:这一段的格子可能全被环节藏了,那时候它自己会被滤掉
sectionFor(field, page)
continue
}
plan.total += 1
if (field.mobileHidden) {
plan.hidden += 1
continue
}
// 那一整页都是别人的系统:格子照样不摆(桌面上也一样看不见),归进那张「打开」卡片
if (isEmbedTab(page)) {
plan.dropped += 1
continue
}
if (perms[field.key] === 'hidden' || field.hidden) {
plan.dropped += 1
continue
}
sectionFor(field, page).rows.push(rowOf(field))
}
}
if (pages.length) {
// 一页一节,按页签的顺序走:容器那一格在数组里排第几,跟"这是第几页"没关系
pages.forEach((tab) => {
const list = fields.filter((field) => !isTabsField(field) && tabKeyOf(field, pages) === tab.key)
if (isEmbedTab(tab)) {
pushEmbedSection(tab)
// 压在外部页面那一页上的格子也记一笔:它们真的在表单里,只是哪儿都不显示
list.forEach((field) => {
if (isLayoutField(field)) return
plan.total += 1
if (field.mobileHidden) plan.hidden += 1
else plan.dropped += 1
})
return
}
walk(list, tab)
})
} else {
walk(fields, null)
}
plan.sections = plan.sections.filter((row) => row.embed || row.rows.length)
return plan
function rowOf(field: FormFieldDef): ReaderRow {
const value = data?.[field.key]
const kind: ReaderRow['kind'] = MEDIA.has(field.type)
? 'media'
: field.type === 'table'
? 'table'
: field.type === 'signature'
? 'signature'
: 'text'
return {
field,
// 签名存的就是那张图,原样交给版式渲染;其余都念成一句人话
text: kind === 'signature' ? (isEmpty(value) ? '' : String(value)) : fieldText(field, value),
empty: isEmpty(value),
kind,
items: kind === 'media' ? filesOf(value) : [],
rows: kind === 'table' && Array.isArray(value) ? (value as Record<string, unknown>[]) : []
}
}
}

View File

@ -0,0 +1,92 @@
import { describe, expect, it, vi } from 'vitest'
import { nextTick, ref } from 'vue'
import { useMobileFeed } from './useMobileFeed'
interface Row {
id: string
}
/** 起一份与 useTableLoader 同款的形状:items / loading / pagination / 换页回调。 */
function harness(total: number) {
const items = ref<Row[]>([])
const loading = ref(false)
const pagination = { page: 1, total, pages: 1 }
const handlePageChange = vi.fn((page: number) => {
pagination.page = page
})
const feedView = useMobileFeed({
items,
loading,
pagination,
handlePageChange,
keyOf: (row) => row.id
})
/** 模拟一次请求回来:先换数据,再让 watch 跑一轮。 */
async function set(rows: Row[]) {
items.value = rows
await nextTick()
}
return { items, loading, pagination, handlePageChange, set, ...feedView }
}
describe('手机上把一页一页攒成一串', () => {
it('第 2 页接在后面,不 put 覆盖掉第 1 页', async () => {
const { pagination, feed, finished, set } = harness(4)
await set([{ id: 'a' }, { id: 'b' }])
expect(feed.value.map((row) => row.id)).toEqual(['a', 'b'])
expect(finished.value).toBe(false)
pagination.page = 2
await set([{ id: 'c' }, { id: 'd' }])
expect(feed.value.map((row) => row.id)).toEqual(['a', 'b', 'c', 'd'])
expect(finished.value).toBe(true)
})
it('回到第 1 页(改了筛选条件)就清掉攒下的那一沓', async () => {
const { pagination, feed, set } = harness(4)
await set([{ id: 'a' }, { id: 'b' }])
pagination.page = 2
await set([{ id: 'c' }])
expect(feed.value).toHaveLength(3)
pagination.page = 1
await set([{ id: 'x' }])
expect(feed.value.map((row) => row.id)).toEqual(['x'])
})
it('两次请求之间插进新单子会让分页窗口后移,同一条落进两页:只留一份', async () => {
const { pagination, feed, set } = harness(5)
await set([{ id: 'a' }, { id: 'b' }])
pagination.page = 2
await set([{ id: 'b' }, { id: 'c' }])
expect(feed.value.map((row) => row.id)).toEqual(['a', 'b', 'c'])
})
it('往回翻是重新给这一页,不是把同一段再接一遍', async () => {
const { pagination, feed, set } = harness(6)
await set([{ id: 'a' }])
pagination.page = 2
await set([{ id: 'b' }])
pagination.page = 1
await set([{ id: 'a' }])
expect(feed.value.map((row) => row.id)).toEqual(['a'])
})
it('加载中不许抢下一页,到底了也不许', async () => {
const { loading, pagination, handlePageChange, loadMore, set } = harness(4)
await set([{ id: 'a' }, { id: 'b' }])
loading.value = true
loadMore()
expect(handlePageChange).not.toHaveBeenCalled()
loading.value = false
loadMore()
expect(handlePageChange).toHaveBeenCalledWith(2)
pagination.page = 2
await set([{ id: 'c' }, { id: 'd' }])
handlePageChange.mockClear()
loadMore()
expect(handlePageChange).not.toHaveBeenCalled()
})
})

View File

@ -0,0 +1,54 @@
import { computed, ref, watch, type Ref } from 'vue'
/**
* 手机上「往下滑就接着给」的翻页收集器。
*
* useOAList 换页时是整批替换(表格那侧要的就是这个行为),手机版式却要把第 1、2、3 页
* 接成一串,否则滑到第 2 页第 1 页就没了。这段逻辑原先长在 TodoListView 里,现在已办、
* 待阅、已阅、我发起的都要用同一双手,抽出来一份,免得五处各写各的、翻页行为各不相同。
*
* 三条规矩跟着一起抽了过来:改筛选条件回到第 1 页时清掉攒下的那一沓(不留上次筛选的残行)、
* 往回翻也重置(不然同一页会被接两遍)、按 id 去重(后端在两次请求之间插进新单子时,
* 分页窗口会整体后移,同一条可能在两页里都出现)。
*/
interface FeedPagination {
page: number
total: number
}
export function useMobileFeed<T>(options: {
items: Ref<T[]>
loading: Ref<boolean>
pagination: FeedPagination
handlePageChange: (page: number) => void
keyOf: (row: T) => string | number
}) {
const { items, loading, pagination, handlePageChange, keyOf } = options
const feed = ref<T[]>([]) as Ref<T[]>
const seenPage = ref(1)
watch(
[() => items.value, () => pagination.page],
([rows, page]) => {
if (page <= 1 || page < seenPage.value) {
feed.value = [...rows]
} else {
const known = new Set(feed.value.map(keyOf))
feed.value = [...feed.value, ...rows.filter((row) => !known.has(keyOf(row)))]
}
seenPage.value = page
},
{ immediate: true }
)
/** 攒够总数就算到底:这一句决定列表末尾是「加载更多」还是「没有更多了」。 */
const finished = computed(() => !loading.value && feed.value.length >= pagination.total)
function loadMore() {
if (loading.value || finished.value) return
handlePageChange(pagination.page + 1)
}
return { feed, finished, loadMore }
}

View File

@ -0,0 +1,132 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, h, type Ref } from 'vue'
import { enableAutoUnmount, mount } from '@vue/test-utils'
import { usePullToRefresh, useRefreshOnReturn, type PullState } from './useMobileRefresh'
/**
* 详情页撤掉刷新按钮之后,「取新数据」这件事只剩这两条道,所以这两条得钉住:
* 下拉这一把手势什么时候算数、什么时候该让位给正常滚动;以及切回前台补取一次。
*
* 监听挂在 window 上,所以每份测试都得先卸掉上一份的组件,否则上一个用例的
* 手势会连着把这一个用例的 load 也叫起来。
*/
enableAutoUnmount(afterEach)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function fire(type: 'touchstart' | 'touchmove' | 'touchend' | 'touchcancel', clientY?: number): any {
const event = new Event(type, { cancelable: true }) as any
if (clientY !== undefined) event.touches = [{ clientY }]
window.dispatchEvent(event)
return event
}
function setScrollY(value: number) {
Object.defineProperty(window, 'scrollY', { value, writable: true, configurable: true })
}
function harness(load: () => unknown, enabled?: () => boolean) {
let state!: Ref<PullState>
mount(
defineComponent({
setup() {
const r = usePullToRefresh(load, enabled)
state = r.state
return () => h('div')
}
})
)
return { state: () => state.value }
}
beforeEach(() => setScrollY(0))
afterEach(() => setScrollY(0))
describe('下拉刷新', () => {
it('拖到顶上越过阈值、松手才刷新;半路松手不算', async () => {
const load = vi.fn().mockResolvedValue(undefined)
const { state: view } = harness(load)
fire('touchstart', 100)
fire('touchmove', 160) // 拖了 60px,阻尼后 30:还没到阈值
expect(view()).toBe('pull')
fire('touchend')
expect(load).not.toHaveBeenCalled()
expect(view()).toBe('hidden')
fire('touchstart', 100)
fire('touchmove', 260) // 160px,阻尼后 80:过了阈值
expect(view()).toBe('ready')
fire('touchend')
expect(view()).toBe('loading')
expect(load).toHaveBeenCalledTimes(1)
await Promise.resolve()
expect(view()).toBe('hidden')
})
it('页面还没滚到顶、或者往上滑,这一把手势就让位给正常滚动', () => {
const load = vi.fn()
harness(load)
setScrollY(240)
fire('touchstart', 100)
const scrolled = fire('touchmove', 300)
expect(scrolled.defaultPrevented).toBe(false)
fire('touchend')
expect(load).not.toHaveBeenCalled()
setScrollY(0)
fire('touchstart', 300)
fire('touchmove', 180) // 往上拖
fire('touchend')
expect(load).not.toHaveBeenCalled()
})
it('禁用时整条手势不接管,也不抢 preventDefault', () => {
const load = vi.fn()
harness(load, () => false)
fire('touchstart', 100)
const move = fire('touchmove', 300)
expect(move.defaultPrevented).toBe(false)
fire('touchend')
expect(load).not.toHaveBeenCalled()
})
it('卸载之后不再监听,切走的页面不该还在替人刷新', () => {
const load = vi.fn()
let state!: Ref<PullState>
const wrapper = mount(
defineComponent({
setup() {
state = usePullToRefresh(load).state
return () => h('div')
}
})
)
wrapper.unmount()
fire('touchstart', 100)
fire('touchmove', 300)
fire('touchend')
expect(load).not.toHaveBeenCalled()
expect(state.value).toBe('hidden')
})
it('回到前台补取一次', () => {
const reload = vi.fn()
const wrapper = mount(
defineComponent({
setup: () => {
useRefreshOnReturn(reload)
return () => h('div')
}
})
)
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
document.dispatchEvent(new Event('visibilitychange'))
expect(reload).not.toHaveBeenCalled()
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
document.dispatchEvent(new Event('visibilitychange'))
expect(reload).toHaveBeenCalledTimes(1)
wrapper.unmount()
document.dispatchEvent(new Event('visibilitychange'))
expect(reload).toHaveBeenCalledTimes(1)
})
})

View File

@ -0,0 +1,102 @@
import { onBeforeUnmount, onMounted, ref } from 'vue'
/**
* 手机上「刷新」不该是一颗按钮。
*
* 详情页顶部那颗刷新图标在 390 上是全场离拇指最远的一次点击,而所有移动端 App 都把刷新
* 放进「下拉」这一把手势里。这一层只跟手势、自己不动scrollTop,所以只在页面已经滚到顶、
* 手指又继续往下拖时才接管;正常往上滚、在弹层里滚、横滑都不碰它。
*
* 另一条不用手的道是 `useRefreshOnReturn`:企微里点开单子、切回去聊两句、再切回来,
* 这中间单子早被人批掉一环了。只读那一屏就该在回到前台时自己取一次。
*/
export type PullState = 'hidden' | 'pull' | 'ready' | 'loading'
/** 起手要拖过这么多像素才认定是下拉,不是按歪了 */
const ARM = 12
/** 拖到这儿就算真的想刷新 */
const THRESHOLD = 56
/** 再往下就是橡皮筋,别让抬头被拽走一大截 */
const MAX = 92
/** 手指位移换成位移条的阻尼:跟手,但不 1:1 地把内容拽跑 */
const DAMPING = 0.5
export function usePullToRefresh(load: () => unknown, enabled: () => boolean = () => true) {
const state = ref<PullState>('hidden')
const pull = ref(0)
let startY = 0
let tracking = false
function reset() {
pull.value = 0
state.value = 'hidden'
}
function onStart(event: TouchEvent) {
tracking = false
if (state.value === 'loading' || !enabled()) return
if (event.touches.length !== 1 || window.scrollY > 0) return
startY = event.touches[0]!.clientY
tracking = true
}
function onMove(event: TouchEvent) {
if (!tracking) return
const dy = event.touches[0]!.clientY - startY
// 往上拖是要滚内容,这一把手势当场放弃
if (dy <= 0) {
tracking = false
reset()
return
}
if (dy < ARM) return
if (window.scrollY > 0) {
tracking = false
reset()
return
}
event.preventDefault()
pull.value = Math.min(MAX, dy * DAMPING)
state.value = pull.value >= THRESHOLD ? 'ready' : 'pull'
}
async function onEnd() {
if (!tracking) return
tracking = false
if (state.value !== 'ready') {
reset()
return
}
state.value = 'loading'
pull.value = THRESHOLD
try {
await load()
} finally {
reset()
}
}
onMounted(() => {
window.addEventListener('touchstart', onStart, { passive: true })
window.addEventListener('touchmove', onMove, { passive: false })
window.addEventListener('touchend', onEnd)
window.addEventListener('touchcancel', onEnd)
})
onBeforeUnmount(() => {
window.removeEventListener('touchstart', onStart)
window.removeEventListener('touchmove', onMove)
window.removeEventListener('touchend', onEnd)
window.removeEventListener('touchcancel', onEnd)
})
return { state, pull }
}
/** 从后台回到前台就取一次:只读那一屏用,正在填单子的屏别拿它抹掉人家写了一半的字。 */
export function useRefreshOnReturn(reload: () => void) {
function onVisibility() {
if (document.visibilityState === 'visible') reload()
}
onMounted(() => document.addEventListener('visibilitychange', onVisibility))
onBeforeUnmount(() => document.removeEventListener('visibilitychange', onVisibility))
}

View File

@ -0,0 +1,89 @@
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMediaQuery } from '@vueuse/core'
/**
* 「这台设备要不要用手机版面」的判据,全站只此一份。
*
* 与 useViewport 的 NARROW(1024) 不同一条线:那一档说的是「侧边栏收进抽屉、底部标签栏接手」,
* 平板也适用;这里问的是另一件事——要不要把审批页换成竖屏那套版式。768 以下才是真手机,
* 拿 1024 去判,10 寸平板会被强行塞进只有一列的手机版,白白浪费半屏。
*
* 判据只在版式这一层用,权限、按钮能不能点、字段能不能编辑一律不看屏幕宽度:
* 同一张单子在手机上能批,在电脑上就得同样能批,反过来也是。
*/
export const PHONE_QUERY = '(max-width: 767.98px)'
/** 领导偶尔要看完整版面(改字段、看流程图):记住他的选择,别每次进来都赶他回手机版 */
const PIN_DESKTOP_KEY = 'oa.mobile.desktop'
/** 字号:手机上给三档,比让领导去翻系统设置现实 */
const FONT_KEY = 'oa.mobile.fs'
export type FontScale = 'm' | 'l' | 'xl'
function read(key: string, fallback = ''): string {
try {
return window.localStorage.getItem(key) ?? fallback
} catch {
return fallback
}
}
function write(key: string, value: string | null) {
try {
if (value === null) window.localStorage.removeItem(key)
else window.localStorage.setItem(key, value)
} catch {
/* 无痕模式下写不进去,不影响功能 */
}
}
const isPhone = useMediaQuery(PHONE_QUERY)
const desktopPinned = ref(read(PIN_DESKTOP_KEY) === '1')
const fontScale = ref<FontScale>((read(FONT_KEY) as FontScale) || 'm')
/** 字号靠 html 的 font-size 整体缩放:Tailwind 的字号、间距都是 rem,一处改完全屏跟着走 */
export function applyFontScale(scale: FontScale) {
if (typeof document === 'undefined') return
if (scale === 'm') document.documentElement.removeAttribute('data-oa-fs')
else document.documentElement.setAttribute('data-oa-fs', scale)
}
// 模块加载即生效:登录页、免登落地页也该带着这个字号,不该等到进主界面才变
applyFontScale(fontScale.value)
export function useMobileShell() {
function pinDesktop(on: boolean) {
desktopPinned.value = on
write(PIN_DESKTOP_KEY, on ? '1' : null)
}
function setFontScale(scale: FontScale) {
fontScale.value = scale
write(FONT_KEY, scale === 'm' ? null : scale)
applyFontScale(scale)
}
return {
isPhone,
desktopPinned,
/** 手机版面的总闸:窄屏 + 没被人为钉在电脑版 */
phoneShell: computed(() => isPhone.value && !desktopPinned.value),
pinDesktop,
fontScale,
setFontScale
}
}
/**
* 「这一页要不要把顶部栏和底部标签栏都让掉」。
*
* 两条都得满足:路由自己标了 chromeless,并且当前真的走的是手机版面。少了后一条,
* 10 寸平板上标签栏也没了,而那一档用的还是桌面版式——桌面版式那条吸底操作栏是按
* 「底下有条标签栏,我抬 3.5rem」摆的(views/oa/TaskDetailView.vue 里那句
* `max-lg:bottom-[...]`),标签栏一没,它就凭空悬在半空。
*/
export function useChromeless() {
const route = useRoute()
const { phoneShell } = useMobileShell()
return {
chromeless: computed(() => route.meta?.chromeless === true && phoneShell.value)
}
}

View File

@ -0,0 +1,434 @@
/**
* 手机版式的预览台(只在开发模式用,不进产物)。
*
* 手机版式值不值,看代码看不出,得真在 390px 宽的屏上摆出来看。这个页面直接挂真的
* 手机版式组件、吃真的 Tailwind、走真的词条,只是数据用 mobileFixtures 里那份假单子——
* 于是没有后端、没有登录,也能把每一屏截下来对一遍。
*
* 开法:`pnpm dev` 之后访问 http://localhost:3000/preview-mobile.html?screen=detail
*
* 两张表单形状换着看:`&form=tabs`(生产上那张分两页的报销单)、
* `&form=custom`(开了「手机端」面板那一档:手机上只出一节,摆什么照配置)。
*/
import { createApp, h, ref } from 'vue'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import Icon from '@/components/icons/Icon.vue'
import MobileCardList from '@/components/oa/mobile/MobileCardList.vue'
import type { MobileCardRow } from '@/components/oa/mobile/MobileCardList.vue'
import MobileLayoutPanel from '@/components/oa/design/MobileLayoutPanel.vue'
import MobileHome from '@/components/oa/mobile/MobileHome.vue'
import type { MobileHomeCounts } from '@/components/oa/mobile/MobileHome.vue'
import MobileTaskView from '@/components/oa/mobile/MobileTaskView.vue'
import MobileWorkView from '@/components/oa/mobile/MobileWorkView.vue'
import ProfileView from '@/views/oa/ProfileView.vue'
import { TASK_VIEW_KEY } from '@/components/oa/mobile/taskContext'
import { useAuthStore } from '@/stores/auth'
import { expenseDetail, expenseSchema, stubView } from '@/components/oa/mobile/mobileFixtures'
import type { FormFieldDef, FormSchema } from '@/types'
import { startOfWork } from '@/utils/approvalRecord'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import '@/style.css'
const params = new URLSearchParams(window.location.search)
const screen = params.get('screen') || 'list'
const open = params.get('open') || ''
// `blocked=1`:把「退回修改」这条出口的适用条件设成不成立,看那一屏怎么说为什么走不了
const blocked = params.get('blocked') ? ['退回修改'] : []
// `form=tabs`:换成生产上那张费用报销单的形状——一张「标签页」分两页,第二页整页是外部系统。
// 手机版式的分节、外部页面那一页、逐格「手机上不展示」,只有在这种表上才看得出对不对。
const formKind = params.get('form') || ''
const paginated = formKind === 'tabs'
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
function listRows(): MobileCardRow[] {
const seed = [
{
title: '差旅报销 · 上海—北京客户巡访',
who: '李明',
dept: '软件开发事业部',
when: '2 小时前',
step: '总经理审批',
note: '超时 1 天',
level: 'danger' as const,
press: '催办 2'
},
{
title: '公文用章申请 · 与华字合作的补充协议',
who: '周静婕',
dept: '经营管理部',
when: '昨天 16:20',
step: '总经理审批',
note: '3 天后到期',
level: 'warn' as const,
press: '4 个出口'
},
{
title: '请假申请 · 事假 2 天',
who: '刘瑞',
dept: '软件开发事业部',
when: '前天 09:10',
step: '总经理审批',
note: '已由他人办理',
level: '' as const,
press: ''
},
{
title: '采购付款申请 · 测试服务器配件',
who: '张南',
dept: '技术支撑中心',
when: '3 天前',
step: '总经理审批',
note: '今天 18:00 到期',
level: 'warn' as const,
press: '催办 1'
},
{
title: '年度预算调整申报 · 研发中心 Q4',
who: '陈默',
dept: '研发中心',
when: '4 天前',
step: '财务复核',
note: '',
level: '' as const,
press: ''
}
]
return seed.map((row, index) => ({
key: String(index + 1),
title: row.title,
meta: [row.who, row.dept, row.when],
badges: [
{ text: row.step, cls: 'badge-primary' },
...(row.note
? [
{
text: row.note,
cls: row.level === 'danger' ? 'badge-danger' : row.level === 'warn' ? 'badge-warning' : 'badge-gray'
}
]
: []),
...(row.press ? [{ text: row.press, cls: 'badge-warning' }] : [])
],
tail: '去批',
level: row.level
}))
}
/**
* 首页那五张卡片的假数字(预览台没有后端,MobileHome 给了 seed 就不再打接口)。
* 数字口径与点进去那张列表一致这件事,测试里盯(MobileHome.spec.ts),这里只管摆得对不对。
*/
const homeCounts: MobileHomeCounts = {
todo: 4,
expired: 1,
done: 26,
read: 3,
readDone: 41,
created: 9
}
/** 生产上那张单的形状:两页、第二页整页是外部系统、其中一格勾了「手机上不展示」。 */
function tabsPreviewSchema(): FormSchema {
const host = {
key: 'tabs_host',
label: '标签页',
type: 'tabs',
tabsMode: 'collapse',
tabsDefault: 'expand',
tabs: [{ key: 'tab_1', label: '费用报销基本信息' }, { key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }]
} as unknown as FormFieldDef
// 那张单没有分隔条:分节全靠页签认
const invoicePage = new Set(['contracts'])
const cells = expenseSchema()
.fields.filter((item) => item.type !== 'divider')
.map((item) => ({
...item,
tab: invoicePage.has(item.key) ? 'tab_2' : 'tab_1',
...(item.key === 'secret' ? { mobileHidden: true } : {})
}))
return { fields: [host, ...cells], layout: { columns: 3 } }
}
/**
* `form=custom`:开了「手机端」面板那一档的样子——手机上只出一节。
*
* 这一档要眼看的正是"配成什么样就是什么样":节名、顺序、哪几格上屏、明细摊不摊开、
* 金额上不上抬头、末尾有没有「完整单据」,全在这份配置里,预览台把它摆出来对一遍。
*/
function customPreviewSchema(): FormSchema {
const base = tabsPreviewSchema()
return {
...base,
layout: {
...(base.layout ?? {}),
mobile: {
enabled: true,
title: '费用报销基本信息',
showFullSheet: false,
fields: [
{ key: 'reason', style: 'block', label: '事由' },
{ key: 'amount', style: 'float' },
{ key: 'approved', style: 'float' },
{ key: 'days' },
{ key: 'trip' },
{ key: 'city' },
{ key: 'empty_note' },
{ key: 'starter' },
{ key: 'starter_dept' },
{ key: 'rows', style: 'list' },
{ key: 'invoices', style: 'gallery' },
// 「标签页」第二页整页是别人的系统:手机上给一张「打开」卡片,配置里点它的键带页签
{ key: 'tabs_host#tab_2', style: 'embed' }
]
}
}
}
}
/** 这一档只换表单内容,数据仍是那份假单子:十二行明细、两张发票、一多半空着的格子。 */
const customPreview = formKind === 'custom'
const keyword = ref('')
const previewDetail = expenseDetail(open === 'readonly' ? { can_process: false } : {})
if (paginated) previewDetail.forms = [{ ...previewDetail.forms[0], content: tabsPreviewSchema() }]
if (customPreview) previewDetail.forms = [{ ...previewDetail.forms[0], content: customPreviewSchema() }]
const previewView = stubView(previewDetail, {
requiredMissing: open === 'missing' ? ['出差天数'] : [],
frozen: open === 'frozen',
blocked
})
function render() {
if (screen === 'home') {
return h(MobileHome, { seed: homeCounts })
}
if (screen === 'profile') {
// 「我的」那一格:通知、收款账户、入口、外观、退出
return h(ProfileView)
}
if (screen === 'list') {
return h(MobileCardList, {
title: '待办',
rows: listRows(),
total: 4,
expired: 1,
finished: true,
keyword: keyword.value,
'onUpdate:keyword': (value: string) => (keyword.value = value),
emptyHint: '暂时没有待办',
onOpen: () => undefined,
onLoadMore: () => undefined,
onRefresh: () => undefined
})
}
if (screen === 'work') {
// 单据详情:已办 / 我发起的 / 待阅 / 通知点进去那一屏,只读
return h(MobileWorkView, {
detail: previewDetail,
formSchema: previewDetail.forms[0]?.content ?? null,
startRecord: startOfWork(previewDetail),
canPress: true,
canIntervene: true,
myIdentity: 'preview'
})
}
if (screen === 'panel') {
// 设计器那个「手机端」面板本身:清单排得顺不顺,得当着桌面宽度摆一次才知道
return h(MobileLayoutPanel, {
show: true,
fields: customPreviewSchema().fields,
layout: (customPreviewSchema().layout as { mobile?: never } | undefined)?.mobile ?? null,
fallbackTitle: '费用报销基本信息'
})
}
return h(MobileTaskView)
}
/**
* 列表那一档外层是 AppLayout:`main` 有 16px 内边距、底下让出标签栏那一段。
* 预览台不挂整套布局,就把这两件事照做一遍,免得在这儿看着对、进了应用差一截。
* 详情那一档是 chromeless 的,自己管整块屏,所以不加。
*/
/** 底部标签栏长这样、多高(真身是 layout/MobileTabBar.vue,这里不重挂一份判据)。 */
function tabBar() {
const items: { icon: string; label: string; on?: boolean; badge?: number }[] = [
{ icon: 'home', label: '首页', on: screen === 'home' },
{
icon: 'inbox',
label: '待办',
on: screen === 'list',
badge: homeCounts.todo
},
{ icon: 'user', label: '我的', on: screen === 'profile' }
]
return h(
'nav',
{
class:
'fixed inset-x-0 bottom-0 z-30 flex border-t border-gray-200 bg-white/95 pb-[env(safe-area-inset-bottom)] backdrop-blur dark:border-dark-700 dark:bg-dark-900/95'
},
items.map((item) =>
h(
'span',
{
class: `flex h-14 flex-1 flex-col items-center justify-center gap-0.5 ${item.on ? 'text-primary-600' : 'text-gray-500'}`
},
[
h(
'span',
{
class: 'relative flex h-7 w-12 items-center justify-center rounded-full'
},
[
h(Icon, { name: item.icon as never, class: 'h-5 w-5' }),
...(item.badge
? [
h(
'span',
{
class:
'absolute -right-0.5 -top-1 min-w-[16px] rounded-full bg-red-500 px-1 text-center text-[10px] font-semibold leading-4 text-white'
},
String(item.badge)
)
]
: [])
]
),
h('span', { class: 'text-[11px] leading-none' }, item.label)
]
)
)
)
}
function renderShell() {
if (screen !== 'list' && screen !== 'home' && screen !== 'profile') return render()
return h('div', { class: 'min-h-screen bg-gray-50 dark:bg-dark-950' }, [
h('main', { class: 'p-4 pb-[4.5rem]' }, h('div', { class: 'app-shell' }, render())),
tabBar()
])
}
const app = createApp({ render: renderShell })
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component: { render: () => null } },
{ path: '/todo', name: 'my-todo', component: { render: () => null } },
{
path: '/todo/:id',
name: 'todo-detail',
component: { render: () => null }
},
{ path: '/done', component: { render: () => null } },
{ path: '/read', component: { render: () => null } },
{ path: '/created', component: { render: () => null } },
{ path: '/start', component: { render: () => null } },
{ path: '/draft', component: { render: () => null } },
{ path: '/home', component: { render: () => null } },
{ path: '/work/:job', name: 'work-detail', component: { render: () => null } },
{ path: '/content/meetings', component: { render: () => null } },
{ path: '/content/schedules', component: { render: () => null } },
{ path: '/content/files', component: { render: () => null } },
{ path: '/monitor', component: { render: () => null } },
{ path: '/statistics', component: { render: () => null } },
{ path: '/settings', component: { render: () => null } },
{ path: '/agent', component: { render: () => null } },
{ path: '/handover', component: { render: () => null } },
{ path: '/help', component: { render: () => null } },
{
path: '/work-print/:job',
name: 'work-print',
component: { render: () => null }
}
]
})
const pinia = createPinia()
app.use(pinia)
// 预览台没登录:直接编一个带全部权限的用户,五张卡片才齐
setActivePinia(pinia)
useAuthStore().$patch({
token: 'preview',
user: {
id: 'u-preview',
account: 'preview',
display_name: '周总',
organization_name: '经营管理部',
is_admin: true
}
} as never)
app.use(i18n)
app.use(router)
app.provide(TASK_VIEW_KEY, previewView)
app.mount('#app')
/**
* 预览用:把要看的那一层自己点开,截屏的人不必模拟手指。
* 只点导航那一步,不点提交——点了就把这张假单子办走了。
*/
function clickText(scope: ParentNode, text: string): boolean {
const hit = Array.from(scope.querySelectorAll<HTMLElement>('button')).find((btn) =>
(btn.textContent || '').includes(text)
)
if (!hit) return false
hit.click()
return true
}
const wait = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms))
window.addEventListener('load', async () => {
await wait(120)
if (open === 'progress') {
document.querySelector<HTMLElement>('[data-test="m-work-tab-progress"]')?.click()
}
if (open === 'pull') {
// 下拉刷新那一格的实拍:只起手不松手,胶囊就停在「松开刷新」这一档
const fire = (type: string, clientY?: number) => {
const event = new Event(type, { cancelable: true }) as Event & { touches?: { clientY: number }[] }
if (clientY !== undefined) event.touches = [{ clientY }]
window.dispatchEvent(event)
}
fire('touchstart', 120)
fire('touchmove', 300)
}
if (open === 'routes' || open === 'approve') {
document.querySelector<HTMLElement>('[data-test="m-agree"]')?.click()
if (open === 'approve') {
await wait(60)
document.querySelectorAll<HTMLElement>('[data-test="m-routes"] [data-test="m-route"]')[0]?.click()
}
}
if (open === 'menu' || open === 'reader' || open === 'people') {
document.querySelector<HTMLElement>('[data-test="m-more"]')?.click()
}
if (open === 'goback') {
document.querySelector<HTMLElement>('[data-test="m-goback"]')?.click()
}
// 「我的」那一格:把通知弹层或收款账户那层直接摊开,截屏的人不必模拟手指
if (open === 'dark') document.documentElement.classList.add('dark')
if (open === 'notice') document.querySelector<HTMLElement>('[data-test="m-bell"]')?.click()
if (open === 'bank') document.querySelector<HTMLElement>('[data-test="m-bank-open"]')?.click()
await wait(60)
if (open === 'progress') clickText(document, '审批记录')
if (open === 'rows') clickText(document, '条')
if (open === 'people') clickText(document, '抄送')
if (open === 'reader') clickText(document, '完整单据')
if (open === 'filled') previewView.opinion.value = '同意,注意下月额度。'
// 弹层是点了才挂上去的,紧接着就量位置会量到一个还不存在的容器
await wait(120)
const to = params.get('scroll')
if (to) {
// 「完整单据」那一层是自己滚的,滚 window 到不了底下那几节
const sheet = document.querySelector<HTMLElement>('[data-test="m-work-reader"] .overflow-y-auto, [data-test="m-reader"] .overflow-y-auto')
if (sheet) sheet.scrollTop = Number(to)
else window.scrollTo({ top: Number(to) })
}
})

View File

@ -132,7 +132,130 @@ export default {
todo: 'To-dos',
start: 'Start',
mine: 'Me',
offline: 'You are offline. This page shows what was loaded last; submitting and approving need a connection.'
offline: 'You are offline. This page shows what was loaded last; submitting and approving need a connection.',
// Everything below belongs to the phone layout (what WeCom opens); see composables/useMobileShell.ts
searchPlaceholder: 'Title, serial or initiator',
loadMore: 'Load more',
noMore: 'Nothing else',
goApprove: 'Approve',
fieldCount: '{count}',
needFill: 'To fill here',
needFillHint: '{count} fields',
fillBeforeApprove: 'Fill these first: {fields}',
// One-tap opinions: nobody wants to type under a thumb on a phone
// An array on purpose: t() reads "|" as a plural separator and would keep only the first form
phrases: ['Approved', 'Agree', 'Noted', 'Please check invoice compliance', 'Approved, mind next month budget'],
lookAgain: 'Not yet',
submitNext: 'Submit, next one',
pickRoute: 'Pick a route',
pickRouteHint: 'This step offers {count} routes; pick one, then add a note',
routeByCondition: 'Target decided by condition',
routeBlocked: 'Condition not met',
routeBlockedCount: '{count} of them cannot be taken right now',
routeTo: '{name} → {target}',
goBackHint: 'They redo this stretch; your note goes with it',
change: 'Edit',
viewFull: 'Full record',
fullHint: '{total} fields, {hidden} empty hidden',
fullSheetDesc: 'Read-only. Field permissions of this step decide what is editable: {editable} here',
fullSheetReadonly: 'Read-only. To edit this record, go back to the step that raised it, or use a desktop.',
// Footnote on the full-document sheet: say who hid those cells, or the sheet just looks short.
fullSheetHidden: '{count} cells are set to "Hide on mobile" and stay off this screen; set per cell in the form designer',
embedPage: 'External page',
// No refresh button on the mobile detail pages: pull to refresh, plus a silent
// re-fetch when the tab comes back to the foreground.
pullMore: 'Keep pulling',
pullReady: 'Release to refresh',
pullLoading: 'Refreshing...',
rowsCount: '{count} rows',
rowsSum: 'Total {sum}',
rowIndex: 'Row {index}',
autoFields: 'Filled by system',
// The form designer's "Mobile" panel: with it on, the phone shows one section built from this config
layoutEntry: 'Mobile',
layoutEntryHint: 'How the form reads on a phone. Off means fields are grouped by type; turn it on and the phone shows one section whose fields, order and layout come from this panel.',
layoutBadgeAuto: 'Auto',
layoutBadgeCustom: 'Configured',
layoutTitle: 'Mobile form',
layoutIntro: 'Left off, the phone groups the form by field type: sections per tab or divider, system values folded into one row, and a "Full sheet" entry at the end. Turn this on and the phone shows a single section — which fields, in what order, and how each one reads all come from the list below. Desktop, print, export and required checks are untouched.',
layoutEnable: 'Show this layout on mobile',
layoutOffHint: 'Automatic grouping is on now. Tick this and the phone shows one section you can edit below.',
layoutSection: 'Section title',
layoutSectionHint: 'Leave empty to use the first tab name; with no tabs it reads "Form data".',
layoutShowFull: 'Keep the "Full sheet" entry',
layoutShowFullHint: 'That screen unfolds every field including the empty ones. Drop it if you want just the one section.',
layoutList: 'Fields to show (top to bottom is the order on screen)',
layoutUp: 'Move up',
layoutDown: 'Move down',
layoutShow: 'Show',
layoutHide: 'Hide',
layoutAlias: 'Label on mobile',
layoutAliasPlaceholder: 'Empty keeps the field label',
layoutStyleLabel: 'Layout',
layoutEmpty: 'This form has no fields that can go on the phone screen yet.',
layoutFloatNote: 'Fields set to "Float" land in the big numbers row in the header, three at most; the rest stay in the section in order.',
layoutPermNote: 'Activity field permissions and the per-field "hidden" switches still apply: a field that step may not see stays off screen.',
layoutStat: '{shown} on screen · {hidden} hidden',
layoutEmbedNote:
'The "External page" rows are whole pages of someone else\'s system embedded in a tab. They are not fields, so their switch lives in this mobile layout only — the inspector has no such checkbox.',
layoutStyle: {
row: 'One row',
block: 'Full block',
float: 'Float',
gallery: 'Thumbnails',
count: 'Count only',
card: 'Collapse to one row',
list: 'Expand every row',
embed: 'Open card'
},
layoutStyleHint: {
row: 'One row: the question on the left, the answer on the right',
block: 'Full block: label above, content across the width — for long text such as the reason',
float: 'Float: moves into the big numbers row in the header, three at most',
gallery: 'Thumbnails shown inline, tap for the full image',
count: 'One row with the count only ("2 invoices"), no images',
card: 'Collapse into "12 rows · total X", tap to expand',
list: 'Every row expanded as its own block in this section',
embed: 'An "Open" card that shows that page in a new window; no embedded frame on the phone'
},
signed: 'Signed',
fontScale: 'Text size',
fontM: 'Default',
fontL: 'Large',
fontXL: 'Largest',
toDesktop: 'Desktop layout',
toPhone: 'Mobile layout',
// The five tiles on the phone home screen (components/oa/mobile/MobileHome.vue):
// one tile per list, short labels here, the long ones live in the sidebar (nav.*)
home: 'Home',
cardTodo: 'To-dos',
cardDone: 'Done',
cardRead: 'To read',
cardReadDone: 'Read',
cardCreated: 'Started',
// Bottom-right hint on a card: what tapping gets you, never a generic details link
viewWork: 'Open',
viewProgress: 'Progress',
goRead: 'Read',
goHandle: 'Handle',
handledTimes: 'Handled {count}x',
flowEarlier: 'Show {count} earlier',
flowExpand: 'More',
flowCollapse: 'Less',
flowFiles: '{count} files',
flowOn: 'Shown',
flowOff: 'Hidden',
// The "Me" tab (views/oa/ProfileView.vue on phones): notices, shortcuts, look, sign out
noticeUnread: '{count} unread',
noticeAllRead: 'All read',
markAllRead: 'Mark all read',
entries: 'Shortcuts',
appearance: 'Appearance',
darkMode: 'Dark mode',
language: 'Language',
installApp: 'Add to Home Screen',
// This shortcut opens the portal; the "Home" tab means the five tiles, keep them apart
entryPortal: 'Company portal'
},
pwa: {
install: 'Install app',
@ -318,6 +441,8 @@ export default {
handledTimes: 'Handled {count} times',
handledTimesHint: 'One row per case, showing your latest handling; earlier ones stay in the case timeline.',
starter: 'Initiator',
// When a task sits with a delegate, say whose step it came from
empoweredTo: 'Handled on behalf of {name}',
startedAt: 'Arrived',
titleWillUpdate: 'Becomes "{title}" once you submit',
expireAt: 'Due',
@ -385,6 +510,11 @@ export default {
terminateConfirm: 'Terminating stops the process for everyone. Continue?',
terminateReason: 'Reason',
terminateReasonPlaceholder: 'Why is this being terminated? It is stored with the result and history',
terminateReasonRequired:
'Please say why this is being terminated. The sentence is stored with the result and the approval history, and it is the only explanation anyone will find afterwards.',
recordTerminatedBy: 'Terminated by {name}',
recordActedBy: '{action} by {name}',
recordActedByPlain: 'Handled by {name}',
deleteUnstarted: 'Delete this work, which was never started',
deleteUnstartedConfirm:
'This work is still parked at the begin step and was never started. Deleting removes the work and its serial for good, and nobody receives it.',
@ -410,6 +540,7 @@ export default {
logJump: 'Returned straight to the sender',
logEnded: 'Case closed',
logCanceled: 'Case voided',
logTerminated: 'Case terminated',
handler: 'Handler',
completedAt: 'Handled at',
attachments: 'Attachments',
@ -738,6 +869,54 @@ export default {
serialTimingNext: 'Next number',
serialTimingNextBound: '{used} taken this period; the shape comes from the numbering rule on that form box, and this preview does not burn one.',
serialTimingNextUnbound: 'This form is not attached to a process yet, so this is what "first of the period" would look like; each process keeps its own counter.',
// The termination slot: who may terminate, until when, and which writebacks fire on the way out.
// It constrains the initiator only; admins still terminate from monitoring (see backend/app/service/terminate.py).
terminateGroup: 'Termination',
terminateStarter: 'Let the initiator terminate their own request',
terminateStarterOnHint:
'The initiator sees a Terminate button under My requests and on the case page. Turning this off removes the button and the engine rejects the call too: hiding a button without blocking the endpoint only leaves a way around the rule.',
terminateStarterOffHint:
'No Terminate button is shown to the initiator. Use Go back or ask a process admin instead. Admins terminating from process monitoring are not covered by this switch: that is an intervention, a different thing from an initiator cleaning up a case they already handed over.',
terminateWindow: 'Until when may the initiator still terminate',
terminateWindowMode: {
always: 'Any time (default)',
notHandled: 'Not once someone has acted on it',
beforeActivity: 'Not after a given step is reached',
withinHours: 'Not after a given number of hours'
},
terminateWindowHint: {
always: 'No window: the initiator can still terminate the case even when it already sits on the last step.',
notHandled:
'Once anybody other than the initiator has completed a step, they can no longer terminate it. The step the initiator filled themselves does not count: the case had not reached anyone yet, so terminating at that point is close to recalling it.',
beforeActivity:
'Blocked once the case has reached that step, the step itself included. The test is whether it has been there, not whether it is still there: letting the initiator terminate after it moved on would discard what the earlier approver decided.',
withinHours:
'Blocked once that many hours have passed since the case started. Reimbursements usually sit untouched overnight, and this is exactly the next-day change of mind worth blocking.'
},
terminateNode: 'Blocked from which step',
terminateNodePlaceholder: 'Pick a step',
terminateNodeHint: 'After the case reaches this step, this step included, the initiator can no longer terminate it.',
terminateHours: 'Within how many hours of starting',
terminateHoursPlaceholder: 'For example 24',
terminateHoursHint: 'At least {min} hours, 0 would mean never allowed; at most {max} hours.',
terminateNodeRequired: 'Blocking after a given step needs a step.',
terminateNodeMissing: 'That step is no longer on the canvas. Pick another one, or set the window back to any time.',
terminateHoursRequired: 'Blocking after a number of hours needs that number.',
terminateHoursTooLarge: 'At most {max} hours, a full year; anything longer means no limit anyway.',
terminateWriteback: 'Writeback templates to call on termination',
terminateWritebackPlaceholder: 'Pick one or more templates',
terminateWritebackHint:
'Termination enqueues these writebacks. The template itself, what it sends and how failures are handled, still lives on the Integrations page. This slot sits on the process because one form can serve several processes, and whether termination should notify the upstream system cannot be configured for just one of them; termination is also not a step on the canvas, so there is nowhere else to mount it.',
terminateWarnOverlap:
'{name} has terminated checked under when to send as well. Termination then produces two messages with different idempotency keys, they do not merge. Make sure this is not a duplicate.',
terminateWarnDisabled: '{name} is disabled, nothing will be sent when a case terminates.',
terminateWarnForm: '{name} is bound to another form, so terminating a case of this process will not send it.',
terminateSummary: {
off: 'Initiators cannot terminate',
notHandled: 'Blocked for the initiator once someone has acted',
beforeActivity: 'Blocked for the initiator from this step on',
withinHours: 'Blocked for the initiator after the set number of hours'
},
dedupAudit: 'Approver audit',
simulate: 'Dry run',
simulateTip: 'Pick a starter, fill the form, then see whose queue the case lands in, which branch it takes and whether it can finish',
@ -1020,6 +1199,7 @@ export default {
allowTransfer: 'Allow transfer',
allowRecall: 'Allow recall',
allowPress: 'Allow reminder',
allowTerminate: 'Allow termination',
ccRules: 'Auto CC',
ccRuleAdd: 'Add CC rule',
ccEmpty: 'No auto CC yet',
@ -1252,6 +1432,7 @@ export default {
pairFromGateway: 'forked by {name}',
containsSubUnit: 'Include sub-units',
minutesUnit: 'minutes',
hoursUnit: 'hours',
noTimerHint: '0 disables the timer',
splitHint: 'e.g. leave_list',
splitNoTable: 'This form has no detail table to pick; pick one first or type the path by hand.',
@ -1847,6 +2028,10 @@ export default {
hiddenFieldHint:
'This cell stays out of the form everywhere, while its value is still stored and system-filled cells and formulas keep working. To show it in one step, set that step field permission to read only or editable.',
hiddenBadge: 'Hidden',
mobileHiddenField: 'Hide on mobile',
mobileHiddenFieldHint:
'Mobile layout only: this cell stays out of the phone summary and the full document sheet, while desktop, printing, exports and required checks keep it. Tick "Hidden by default" to drop it from the whole flow. For a single phone section with its own field order and layout, use the "Mobile" button in the toolbar.',
mobileHiddenBadge: 'Mobile off',
min: 'Min',
max: 'Max',
step: 'Step',
@ -2398,6 +2583,8 @@ export default {
linkageValueMulti: 'Pick values',
linkageValueManual: 'Org list unavailable - type it',
markRequired: 'Set required',
bulkMobileHide: 'Hide on mobile',
bulkMobileShow: 'Show on mobile',
unmarkRequired: 'Clear required',
alignLeft: 'Align left',
multiSelected: '{count} fields selected, edit them together',
@ -2813,6 +3000,8 @@ export default {
'Only the edited fields are submitted. Each change is written to the flow history as “field: before → after”, and current handlers plus the initiator are notified.',
dataChanged: '{count} field(s) changed',
dataNone: 'No changes',
dataDrift: 'The title disagrees with the form field; saving realigns them',
dataTitleNext: 'The title becomes "{title}" once saved',
dataSave: 'Save changes',
dataDefault: 'Form data corrected by an administrator',
dataDone: 'Form data corrected',
@ -3754,14 +3943,16 @@ export default {
legacyMove: 'Move onto that activity',
firingTitle: 'When it actually fires',
firingLoading: 'Checking whether any activity mounts it...',
firingNone: 'No trigger yet: this template will never send by itself, only by manual replay here. Tick a terminal event, or mount it on an activity in the process designer, to make it fire automatically.',
firingNone: 'No trigger yet: this template will never send by itself, only by manual replay here. Tick a terminal event, mount it on an activity in the process designer, or mount it on a process Terminate block to make it fire automatically.',
firingTerminal: 'Terminal',
firingMount: 'Activity',
firingTerminate: 'Flow terminated',
auditTitle: 'Config check: {count} writeback settings are currently silent or firing twice',
auditExpand: 'Show which',
auditCollapse: 'Collapse',
auditKindTemplate: 'Template',
auditKindMount: 'Mount',
auditKindTerminate: 'Terminate mount',
auditOpenTemplate: 'Open this template',
auditOpenProcess: 'Open in process designer',
eventKeyMissing: 'This activity is gone',

View File

@ -128,7 +128,130 @@ export default {
todo: '待办',
start: '发起',
mine: '我的',
offline: '当前网络不可用,页面显示的是上次打开时的内容;提交与审批要等网络恢复。'
offline: '当前网络不可用,页面显示的是上次打开时的内容;提交与审批要等网络恢复。',
// 以下都是手机版式(企微里打开就是这一档)的文案,判据见 composables/useMobileShell.ts
searchPlaceholder: '搜标题、单号、发起人',
loadMore: '加载更多',
noMore: '没有更多了',
goApprove: '去批',
fieldCount: '{count} 项',
needFill: '本环节要填',
needFillHint: '共 {count} 项',
fillBeforeApprove: '先填这几项:{fields}',
// 一句话意见:点一下就填好,手机上没人愿意在拇指底下打字
// 存成数组:t() 会把 | 当复数分隔符,串着存只会剩第一条
phrases: ['同意', '拟同意', '已阅', '请财务注意发票合规', '同意,注意下月额度'],
lookAgain: '再看看',
submitNext: '提交,看下一条',
pickRoute: '选一个出口',
pickRouteHint: '这一环配了 {count} 条出口,选完再写意见',
routeByCondition: '去向由条件决定',
routeBlocked: '适用条件不成立,走不了',
routeBlockedCount: '其中 {count} 条当前走不了',
routeTo: '{name} → {target}',
goBackHint: '退回后要重走这一段,意见会同步给对方',
change: '改',
viewFull: '完整单据',
fullHint: '{total} 个字段,折了 {hidden} 个空的',
fullSheetDesc: '只读。能改哪几格由这一环的字段权限决定,本环节可改 {editable} 格',
fullSheetReadonly: '只读。要改这一单的内容,回到发起它的那一环或电脑上操作。',
// 完整单据那一屏的脚注:少掉的格子要说得出是谁设的,不然只看见单子短了一截
fullSheetHidden: '有 {count} 格设了「手机上不展示」,这一屏不摆;在表单设计器里逐格设',
embedPage: '外部页面',
// 手机上详情页不给刷新按钮:数据靠下拉这一把手势,加上回到前台时自己取一次
pullMore: '继续下拉',
pullReady: '松开刷新',
pullLoading: '正在刷新…',
rowsCount: '{count} 条',
rowsSum: '合计 {sum}',
rowIndex: '第 {index} 条',
autoFields: '系统取数',
// 表单设计器里的「手机端」面板:开了那一档,手机上只出一节,摆什么照配置
layoutEntry: '手机端',
layoutEntryHint: '手机上「表单内容」那一屏怎么摆。默认按字段类型自动归置;开了自定义就只出一节,摆哪些格子、什么顺序、每格怎么摆都能配。',
layoutBadgeAuto: '自动',
layoutBadgeCustom: '已配置',
layoutTitle: '手机端表单',
layoutIntro: '不开这一档,手机上「表单内容」按字段类型自动归置:按页签和分隔条分节、系统取数并成一行、末尾留一个「完整单据」入口。开了之后手机上只出一节——摆哪些格子、按什么顺序、每格怎么摆,全照下面这一份;电脑、打印、导出、必填校验一概不变。',
layoutEnable: '按这份配置展示',
layoutOffHint: '现在是自动归置。勾上这一档,手机上就只出一节,底下那份清单立刻能改。',
layoutSection: '这一节的名字',
layoutSectionHint: '留空就用表单上第一个页签的名字;没有页签则写「表单内容」。',
layoutShowFull: '末尾留「完整单据」入口',
layoutShowFullHint: '那一屏会把所有格子连空着的都摊开。只要一节的话就别留。',
layoutList: '摆哪些格子(从上到下就是手机上的顺序)',
layoutUp: '上移',
layoutDown: '下移',
layoutShow: '展示',
layoutHide: '不展示',
layoutAlias: '手机上显示为',
layoutAliasPlaceholder: '留空用字段标题',
layoutStyleLabel: '摆法',
layoutEmpty: '这张表单还没有能上手机屏的格子。',
layoutFloatNote: '「置顶」的格子摆到单据抬头那一排大字上,最多三格;多出来的仍回到这一节里按顺序摆。',
layoutPermNote: '环节字段权限和格子上「默认隐藏 / 手机上不展示」照常管用:那一环不让看的格子,这里配了也不上屏。',
layoutStat: '上屏 {shown} 格 · 收起 {hidden} 格',
layoutEmbedNote:
'清单里那几行「外部页面」是标签页里整页嵌进来的别人的系统:它们不是格子,上不上屏只记在这份手机端配置里,属性面板上找不到那颗勾。',
layoutStyle: {
row: '一行',
block: '整段',
float: '置顶',
gallery: '缩略图',
count: '只写数量',
card: '收成一行',
list: '逐条展开',
embed: '打开卡片'
},
layoutStyleHint: {
row: '一行:左边问的是什么,右边是答案',
block: '整段:标签在上,内容摊开一整块,事由这类长文本用这一档',
float: '置顶:上到单据抬头那一排大字,最多三格',
gallery: '缩略图直接摆出来,点开是大图',
count: '只给一行数量(「发票 2」),图不摆',
card: '收成一行「12 条 · 合计 X」,点开才逐条',
list: '一条一段摊在这一节里',
embed: '给一张「打开」卡片,点了在新窗口看那一页;手机上不内嵌别人的系统'
},
signed: '已签名',
fontScale: '字号',
fontM: '标准',
fontL: '大',
fontXL: '特大',
toDesktop: '看电脑版',
toPhone: '看手机版',
// 首页那五张小卡片(components/oa/mobile/MobileHome.vue):一张卡一个列表,
// 名字取短版,长版在侧边栏(nav.myTodo 那一组),两处指的是同一张列表
home: '首页',
cardTodo: '待办',
cardDone: '已办',
cardRead: '待阅',
cardReadDone: '已阅',
cardCreated: '我发起的',
// 卡片列表右下角那句:说清点下去会看见什么,不写「查看详情」这种哪儿都能贴的话
viewWork: '看单据',
viewProgress: '看进度',
goRead: '去阅',
goHandle: '去处理',
handledTimes: '办过 {count} 次',
// 手机上那条流转时间线(components/oa/mobile/MobileFlow.vue)
flowEarlier: '展开更早 {count} 条',
flowExpand: '展开',
flowCollapse: '收起',
flowFiles: '附件 {count}',
flowOn: '已显示',
flowOff: '已隐藏',
// 「我的」那一格(views/oa/ProfileView.vue 的手机档):读通知、找入口、调外观、退出
noticeUnread: '{count} 条未读',
noticeAllRead: '都读过了',
markAllRead: '全部标已读',
entries: '常用入口',
appearance: '外观',
darkMode: '深色模式',
language: '语言',
installApp: '添加到主屏幕',
// 入口里这一格指门户那一屏;底部标签栏那格「首页」指的是工作台那五张卡片,别撞名
entryPortal: '门户资讯'
},
pwa: {
install: '安装到桌面',
@ -314,6 +437,8 @@ export default {
handledTimes: '已处理 {count} 次',
handledTimesHint: '同一条流程只列一条,摆的是最近那次处理;前面几次的意见与流转在详情里一条不少',
starter: '发起人',
// 待办挂在代理人名下:页面上要说清楚是谁把这一步交下来的
empoweredTo: '该待办由 {name} 代理处理',
startedAt: '到达时间',
titleWillUpdate: '提交后会更新为「{title}」',
expireAt: '处理时限',
@ -381,6 +506,10 @@ export default {
terminateConfirm: '终止后流程将无法继续流转,确定终止吗?',
terminateReason: '终止原因',
terminateReasonPlaceholder: '写一句为什么终止,会记进流程结果与审批记录',
terminateReasonRequired: '请写一句为什么终止。这句话会记进流程结果与审批记录,也是别人事后唯一能看到的解释。',
recordTerminatedBy: '由 {name} 终止',
recordActedBy: '由 {name} {action}',
recordActedByPlain: '由 {name} 操作',
deleteUnstarted: '删除这张还没发起的单',
deleteUnstartedConfirm:
'这张单还停在开始环节、没有发起流转。删除后连单带号一起清除,不可恢复,也不会有人收到它。',
@ -406,6 +535,7 @@ export default {
logSerial: '排定流程编号',
logEnded: '流程办结',
logCanceled: '流程作废',
logTerminated: '流程终止',
handler: '处理人',
completedAt: '处理时间',
attachments: '附件',
@ -736,6 +866,54 @@ export default {
serialTimingNext: '下一个编号',
serialTimingNextBound: '本期已排 {used} 个;长什么样由表单那一格的编号规则决定,这里只是预览,不会吃掉一个号。',
serialTimingNextUnbound: '这张表单还没挂到流程上,给的是「本期第一个」的样子;计数器按流程各记一本账。',
// 「终止」那一格:谁能终止、到什么时候为止、终止那一刻再发哪几个写回模板。
// 只管发起人,管理员在流程监控里照样终止得动(判据全在 backend/app/service/terminate.py)。
terminateGroup: '终止',
terminateStarter: '允许发起人终止自己发起的单',
terminateStarterOnHint:
'发起人在「我发起的」和单据详情里能看到「终止」这颗钮。关掉之后这颗钮不再出现,引擎那一侧也一并挡下:只藏按钮不挡接口,等于留一个能绕过规矩的口子。',
terminateStarterOffHint:
'界面上不再出现「终止」这颗钮,单子要收尾请走「退回」或找流程管理员。管理员在流程监控里的终止不受这一格约束:那是干预手段,与发起人收拾自己交出去的单是两件事。',
terminateWindow: '到什么时候为止还允许发起人终止',
terminateWindowMode: {
always: '随时都能终止(默认)',
notHandled: '有人办理之后就不能终止',
beforeActivity: '走到指定环节之后就不能终止',
withinHours: '超过限定小时数之后就不能终止'
},
terminateWindowHint: {
always: '不设窗口:单子哪怕已经跑到最后一环,发起人也能自己把它终止掉。',
notHandled:
'只要除发起人以外有人在这张单上办完过一步,发起人就不能再终止它。发起人自己填的那一步不算:那张单还没落到任何人手上,这时候终止与撤回没多大分别。',
beforeActivity:
'单子到过那一环(含这一环)之后就不能终止。判据是「到过」而不是「还停在那儿」:单子从那一环流走之后再让发起人终止,前面那位审批人的表态就白做了。',
withinHours:
'发起之后过了这个小时数就不能终止。报销单隔夜就没人再动,「第二天想起来才反悔」最该挡的就是这一档。'
},
terminateNode: '到哪一环为止',
terminateNodePlaceholder: '选一个环节',
terminateNodeHint: '单子走到这一环(含这一环)之后,发起人不能再终止这张单。',
terminateHours: '发起后多少小时内',
terminateHoursPlaceholder: '比如 24',
terminateHoursHint: '至少 {min} 小时,填 0 等于从不允许;最多 {max} 小时。',
terminateNodeRequired: '选了「走到指定环节之后就不能终止」,得指一个环节。',
terminateNodeMissing: '这里指的环节已经不在画布上了,重新选一个,或者把窗口改回随时都能终止。',
terminateHoursRequired: '选了「超过限定小时数之后就不能终止」,得填一个小时数。',
terminateHoursTooLarge: '限定小时数最多 {max} 小时(整整一年),再长就等于不设限了。',
terminateWriteback: '终止时调用哪些回写模板',
terminateWritebackPlaceholder: '选一个或多个模板',
terminateWritebackHint:
'终止那一刻按这一格入队写回。模板本体(发什么、怎么发、失败怎么兜)仍旧在「集成写回」页配。这一格之所以长在流程上:同一张表单可能挂着好几条流程,「终止时要不要通知上游」没法只给其中一条配;而终止不是画布上的环节,也挂不到任何一环上。',
terminateWarnOverlap:
'{name} 自己在「什么时候发」里也勾了终止:终止那一刻会各发一条,幂等键不同、不会互相吞并。确认这不是重复配置。',
terminateWarnDisabled: '{name} 当前是停用状态,终止那一刻不会发出去。',
terminateWarnForm: '{name} 绑的是另一张表单,这条流程的单子终止时不会发它。',
terminateSummary: {
off: '发起人不能终止',
notHandled: '有人办理之后发起人不能再终止',
beforeActivity: '走到这一环之后发起人不能再终止',
withinHours: '超过设定小时数之后发起人不能再终止'
},
dedupAudit: '审批体检',
simulate: '试跑预测',
simulateTip: '选个发起人、把表单填全,先看看这一单会落在谁手上、走哪条分支、能不能走到结束',
@ -1018,6 +1196,7 @@ export default {
allowTransfer: '允许转发',
allowRecall: '允许撤回',
allowPress: '允许催办',
allowTerminate: '允许终止',
ccRules: '自动抄送',
ccRuleAdd: '加一条抄送',
ccEmpty: '还没有自动抄送',
@ -1250,6 +1429,7 @@ export default {
pairFromGateway: '由「{name}」分叉而来',
containsSubUnit: '包含下级部门',
minutesUnit: '分钟',
hoursUnit: '小时',
noTimerHint: '0 表示不计时',
splitHint: '如 leave_list',
splitNoTable: '这张表单还没有明细表字段可挑;先选明细表,或直接手写路径。',
@ -1845,6 +2025,10 @@ export default {
hiddenFieldHint:
'整张流程默认都看不到这一格,但值照常保存,系统带出与公式也照总算。哪个环节要显示它,在那个环节的「字段权限」里显式改成只读或可编辑就行。',
hiddenBadge: '隐藏',
mobileHiddenField: '手机上不展示',
mobileHiddenFieldHint:
'只影响手机版式:这一格在手机的单据摘要与「完整单据」里都不出现,电脑、打印、导出、必填校验照旧。整张流程都不想看见它就勾「默认隐藏」。想让手机上只出一节、连顺序和摆法一起定,用工具栏那颗「手机端」。',
mobileHiddenBadge: '手机不展示',
min: '最小值',
max: '最大值',
step: '步长',
@ -2391,6 +2575,8 @@ export default {
linkageValueMulti: '挑多个值',
linkageValueManual: '组织清单没拉到,可手填',
markRequired: '设为必填',
bulkMobileHide: '手机上不展示',
bulkMobileShow: '手机上都展示',
unmarkRequired: '取消必填',
alignLeft: '左对齐',
multiSelected: '已选 {count} 个字段,可批量调整',
@ -2802,6 +2988,8 @@ export default {
dataIntro: '只交改动的那几项。改了什么按「字段:旧值 → 新值」写进流转记录,并知会当前处理人与发起人。',
dataChanged: '改了 {count} 处',
dataNone: '没有改动',
dataDrift: '标题与表单那一格不一致,保存即对齐',
dataTitleNext: '保存后标题会变成「{title}」',
dataSave: '保存修正',
dataDefault: '管理员修正表单数据',
dataDone: '表单数据已修正',
@ -3745,14 +3933,16 @@ export default {
legacyMove: '搬到这个环节上',
firingTitle: '什么时候真的会发',
firingLoading: '正在看流程里有没有环节挂着它…',
firingNone: '还没有触发点:这条模板一条都不会自动发,只能在集成页人工重推。要让它自己发,就勾一条终态,或者到流程设计器把它挂到某个环节上。',
firingNone: '还没有触发点:这条模板一条都不会自动发,只能在集成页人工重推。要让它自己发,就勾一条终态,到流程设计器把它挂到某个环节上,或者挂进某条流程的「终止」那一格。',
firingTerminal: '终态',
firingMount: '环节',
firingTerminate: '流程终止',
auditTitle: '配置体检:{count} 处写回配置现在要么静默不发、要么多发一遍',
auditExpand: '展开看是哪几处',
auditCollapse: '收起',
auditKindTemplate: '写回模板',
auditKindMount: '环节挂载',
auditKindTerminate: '终止挂载',
auditOpenTemplate: '打开这条模板',
auditOpenProcess: '去流程设计器',
eventKeyMissing: '这个环节已经不在了',

View File

@ -2,7 +2,7 @@ import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { applyDocumentTitle } from '@/router/title'
import { clearChunkReloadMark, reloadOnChunkError } from '@/router/chunkReload'
import { recordReturnPath } from '@/utils/returnPath'
import { landingPath, recordReturnPath } from '@/utils/returnPath'
const routes: RouteRecordRaw[] = [
{
@ -23,7 +23,7 @@ const routes: RouteRecordRaw[] = [
path: '/',
component: () => import('@/components/layout/AppLayout.vue'),
children: [
{ path: '', redirect: '/home' },
{ path: '', redirect: () => landingPath() },
{
path: 'home',
name: 'portal-home',
@ -95,7 +95,12 @@ const routes: RouteRecordRaw[] = [
path: 'todo/:id',
name: 'todo-detail',
component: () => import('@/views/oa/TaskDetailView.vue'),
meta: { titleKey: 'nav.myTodo', permission: 'work:todo' }
// chromeless:手机上这张单子多是从企微卡片直接点开的,顶部栏与底部标签栏都让给它自己
meta: {
titleKey: 'nav.myTodo',
permission: 'work:todo',
chromeless: true
}
},
{
path: 'done',
@ -113,7 +118,9 @@ const routes: RouteRecordRaw[] = [
path: 'work/:job',
name: 'work-detail',
component: () => import('@/views/oa/WorkDetailView.vue'),
meta: { titleKey: 'work.detail' }
// chromeless:这一页是「已办 / 我发起的 / 待阅 / 通知 / 监控」共同的落点,手机上由
// MobileWorkView 自己管整块屏(自带返回栏 + 吸底操作位),不能再叠一层顶部栏和标签栏
meta: { titleKey: 'work.detail', chromeless: true }
},
{
path: 'read',
@ -163,7 +170,11 @@ const routes: RouteRecordRaw[] = [
name: 'design-process-editor',
component: () => import('@/views/oa/design/ProcessDesignerView.vue'),
// 画布页要每一像素的横向空间,不参与正文那道 maxWidth 收口(见 AppLayout)
meta: { titleKey: 'process.design', permission: 'design:process', fullWidth: true }
meta: {
titleKey: 'process.design',
permission: 'design:process',
fullWidth: true
}
},
{
path: 'design/forms',
@ -175,7 +186,11 @@ const routes: RouteRecordRaw[] = [
path: 'design/forms/:id',
name: 'design-form-editor',
component: () => import('@/views/oa/design/FormDesignerView.vue'),
meta: { titleKey: 'form.designer', permission: 'design:form', fullWidth: true }
meta: {
titleKey: 'form.designer',
permission: 'design:form',
fullWidth: true
}
},
{
path: 'design/dicts',
@ -188,14 +203,20 @@ const routes: RouteRecordRaw[] = [
path: 'design/data-sources',
name: 'design-data-sources',
component: () => import('@/views/oa/design/DataSourceView.vue'),
meta: { titleKey: 'nav.dataSourceDesign', permission: 'design:datasource' }
meta: {
titleKey: 'nav.dataSourceDesign',
permission: 'design:datasource'
}
},
{
// 集成写回:审批通过后往业务系统发什么、发得怎么样、失败了怎么补
path: 'design/integrations',
name: 'design-integrations',
component: () => import('@/views/oa/design/IntegrationView.vue'),
meta: { titleKey: 'nav.integrationDesign', permission: 'design:integration' }
meta: {
titleKey: 'nav.integrationDesign',
permission: 'design:integration'
}
},
{
// 开放平台:给外部系统的钥匙(应用与授权范围)、事件订阅、接口文档与留痕
@ -308,18 +329,8 @@ const router = createRouter({
scrollBehavior: () => ({ top: 0 })
})
/** Where a user lands when the requested page is outside their permissions. */
const FALLBACK_PATHS: [string, string][] = [
['portal:home', '/home'],
['work:workbench', '/workbench'],
['work:todo', '/todo'],
['work:profile', '/profile']
]
function firstAllowedPath(can: (code: string) => boolean): string {
const hit = FALLBACK_PATHS.find(([code]) => can(code))
return hit ? hit[1] : ''
}
// 权限不够时回落到哪一屏,用的就是 landingPath() 那张表:手机上门户排最后,
// 桌面照旧门户第一。这里不再另立一份顺序,否则「第一屏」和「回退页」会各说一套。
router.beforeEach((to) => {
const authStore = useAuthStore()
@ -329,18 +340,23 @@ router.beforeEach((to) => {
if (to.name === 'login' && typeof to.query.ticket === 'string' && to.query.ticket) {
return { name: 'sso-callback', query: { ...to.query } }
}
if (to.name === 'login' && authStore.isAuthenticated && authStore.can('portal:home')) {
return { name: 'portal-home' }
// 已经登录又撞上 /login(Hub 上那条 launch_url 被人填成登录页):回第一屏,
// 而不是硬塞门户——手机上第一屏该是卡片那一屏,且得是他有权限的那一屏。
if (to.name === 'login' && authStore.isAuthenticated) {
return landingPath()
}
return true
}
if (!authStore.isAuthenticated) {
return { name: 'login', query: to.fullPath === '/' ? {} : { redirect: to.fullPath } }
return {
name: 'login',
query: to.fullPath === '/' ? {} : { redirect: to.fullPath }
}
}
if (to.meta.permission && !authStore.can(to.meta.permission)) {
const fallback = firstAllowedPath((code) => authStore.can(code))
const fallback = landingPath()
// 回退页也进不去时停在登录页,避免来回打转。
return fallback && fallback !== to.path ? fallback : { name: 'login' }
return fallback !== to.path ? fallback : { name: 'login' }
}
return true
})

View File

@ -8,5 +8,14 @@ declare module 'vue-router' {
titleKey?: string
/** 画布类页面(流程/表单设计器)铺满整个内容区,不收进 AppLayout 那道宽度。 */
fullWidth?: boolean
/**
* 手机上这一页自己管整块屏幕:不挂顶部栏、不挂底部标签栏。
*
* 只给「钻进一条记录里办一件事」的页面用(待办详情就是)。那种页面底下要贴一条
* 吸底操作栏,再叠一条常驻标签栏,两道栏加起来吃掉近 120px,「同意」被抬到拇指
* 够不着的地方;返回这件事交给页面自己那颗返回键。宽屏与此无关,判据见
* composables/useMobileShell.ts:useChromeless。
*/
chromeless?: boolean
}
}

View File

@ -8,6 +8,8 @@ import type { PublicSettings, Toast, ToastType } from '@/types'
import { getPublicSettings as fetchPublicSettingsAPI } from '@/api/auth'
import { countProcessing } from '@/api/task'
import { countRead } from '@/api/work'
import { listNotifications, readAllNotifications, readNotification as readOneNotification, unreadCount } from '@/api/support'
import type { NotificationItem } from '@/types'
const SIDEBAR_KEY = 'unisoa_sidebar_collapsed'
@ -29,6 +31,12 @@ export const useAppStore = defineStore('app', () => {
* 否则别人抄给您的单子在那儿躺着,界面上一点动静都没有。
*/
const readCount = ref<number>(0)
/**
* 站内通知:桌面上顶栏那份下拉读它,手机上「消息通知」那一栏也读它。
* 两处各拉一份就会出现「下拉里三条未读,手机那一栏说都读过了」。
*/
const notifications = ref<NotificationItem[]>([])
const notificationUnread = ref<number>(0)
const siteName = ref<string>('UnisOA 流程审批平台')
const siteLogo = ref<string>('/logo.svg')
const siteDescription = ref<string>('')
@ -103,6 +111,27 @@ export const useAppStore = defineStore('app', () => {
const info = (message: string, duration?: number) => showToast('info', message, duration)
const warning = (message: string, duration?: number) => showToast('warning', message, duration)
/** 拉一页通知 + 一次未读数。失败就当没有,不弹红条:这一份是提示,不是数据。 */
async function loadNotifications(): Promise<void> {
try {
const [page, count] = await Promise.all([listNotifications({ page: 1, page_size: 20 }), unreadCount()])
notifications.value = page.items
notificationUnread.value = count.count
} catch {
notifications.value = []
}
}
async function markNotificationsRead(): Promise<void> {
await readAllNotifications().catch(() => undefined)
await loadNotifications()
}
/** 点开一条就算读过:未读数当场减一,省一次往返,也免得读完还挂着角标。 */
async function readNotification(item: NotificationItem): Promise<void> {
if (item.read) return
await readOneNotification(item.id).catch(() => undefined)
item.read = true
notificationUnread.value = Math.max(0, notificationUnread.value - 1)
}
function applyPublicSettings(settings: PublicSettings): void {
cachedPublicSettings.value = settings
siteName.value = (settings.site_name as string) || siteName.value
@ -142,6 +171,11 @@ export const useAppStore = defineStore('app', () => {
mobileOpen,
todoCount,
readCount,
notifications,
notificationUnread,
loadNotifications,
markNotificationsRead,
readNotification,
refreshTodoCount,
refreshReadCount,
refreshBadgeCounts,

View File

@ -958,6 +958,26 @@
}
}
/* 数字用等宽字形:手机上金额、单号、倒计时都是竖着排的,字形宽度不齐时上下两行
会互相错位,看着像没对齐,其实是数字在跳。 */
.num {
font-variant-numeric: tabular-nums;
font-feature-settings: 'tnum' 1;
}
/* 手机上给三档字号:多数人不会去翻系统里的显示设置,页面上给三颗钮更现实。
整套界面走的是 rem(Tailwind 默认),改 html 这一处,字、行高、间距一起跟着走。
只在真手机这一档生效——在电脑上把字号也撑大,那是另一回事了。 */
@media (max-width: 767.98px) {
html[data-oa-fs='l'] {
font-size: 17px;
}
html[data-oa-fs='xl'] {
font-size: 18.5px;
}
}
/* iOS Safari 的规矩:聚焦一个字号不到 16px 的输入框,它就把整页放大一档,
然后回不去——填单子时那是最让人火大的一跳。桌面这边照旧 14px,只动真手机这一档。 */
@media (max-width: 767.98px) {

View File

@ -377,7 +377,7 @@ export interface SerialReservation {
export type SerialTimingWhen = 'enter' | 'leave'
/**
* 办理页的标题实时预览结果:口径在后端 `titles.preview_refresh`。
* 办理页 / 干预面板的标题实时预览结果:口径在后端 `titles.preview_refresh`。
* 与发起页那份的区别是它多说了两句当前状态——`current` 是现在这句,
* `changed` 是「照这么提交,标题会不会真的换」(没开自动重算就是 false)。
*/
@ -403,6 +403,32 @@ export interface ProcessSerialTiming {
when?: SerialTimingWhen
}
/**
* 「发起人到什么时候为止还能终止自己这张单」的四档窗口,与后端
* `service/terminate.py` 的 `UNTIL_*` 一一对应。缺省 `always`:与这份配置
* 存在之前一模一样,存量流程一行都不用迁移。
*/
export type ProcessTerminateUntil = 'always' | 'notHandled' | 'beforeActivity' | 'withinHours'
/**
* 发起人终止的规矩,存在 `oa_process.terminate_config`;空对象等同于「随时都能终止」。
*
* 只管发起人,**不管管理员**:监控里那次终止是干预手段,与发起人收拾自己交出去的单是两件事。
* 口径与判据全在后端 `service/terminate.py`,这里只保证界面写出来的形状它认得。
*/
export interface ProcessTerminateConfig {
/** 关掉:界面上不出现那颗「终止」钮,引擎也挡下(两边读同一个判据) */
allowStarter?: boolean
until?: ProcessTerminateUntil
/** `until=beforeActivity` 时指哪一环(**含**这一环,判"到过"而不是"正停在那儿") */
untilActivity?: string
/** `until=withinHours` 时的小时数,1 ~ 8760 */
untilHours?: number
/**
* 终止那一刻要发哪几个写回模板。时刻固定是 `terminate`(它不是画布上的环节,
* 挂不到任何一环上,所以流程自己留这一格),其余形状与环节挂载完全一致。
*/
writeback?: WritebackMount
}
/**
* 流程标题生成方式:
* - default:不配规则,沿用「表单里的 title/subject/name,否则「某某的XX流程」」
@ -980,6 +1006,21 @@ export interface WritebackFiring {
goBackVia?: string[]
goBackViaText?: string
}>
/**
* 被哪几条流程的「终止时调用哪些回写模板」点名了(`oa_process.terminate_config.writeback`)。
*
* 这一格不挂环节,所以它不在 `mounts` 里,也不该在——合在一份清单里人才不会以为
* 「终止时」只能等模板自己勾终态。口径见 docs/node-writeback-config.md §5.5.1。
*/
terminateMounts?: Array<{
process: string
processName: string
/** 这一格勾中的时刻;目前只有 terminate 一个值,留着是为了与环节那份同形 */
triggers?: WritebackTrigger[]
triggerText?: string
/** 后端拼好的一行:流程名 · 终止(多条规则时点名第几条) */
label: string
}>
}
/**
@ -989,8 +1030,8 @@ export interface WritebackFiring {
* 两头点名。保存那道闸只管当下那一次,所以这一份由后端扫全库给(口径同后端 audit)。
*/
export interface WritebackAuditItem {
/** template = 集成页那一条模板;mount = 某条流程上的环节挂载 */
kind: 'template' | 'mount'
/** template = 集成页那一条模板;mount = 某条流程上的环节挂载;terminate = 流程那一格终止挂载 */
kind: 'template' | 'mount' | 'terminate'
/** kind=template 时的模板编码,点一下就在编辑器里选中它 */
code: string
/** kind=mount 时的流程 id,给「去流程设计器」那个链接 */
@ -1009,12 +1050,17 @@ export interface WritebackAuditItem {
*/
/** 挂载里点名一个模板:只给编码,或带上「这一格才发」的条件 / 「要发的字段」勾选 */
/**
* 环节写回的触发时刻。四个值与后端 `mapping.TRIGGERS` 一一对应:
* 写回的触发时刻。前四个值与后端 `mapping.TRIGGERS` 一一对应:
* `arrive` 到达本环节、`leave` 本环节通过后(同意 / 提交)、`goBack` 本环节被退回、
* `recall` 本环节被撤回。后两个不经过引擎那条流转主线(`go_back` / `reset_task`
* 自己派待办),所以它们只能挂在按按钮的这一环上。
*
* `terminate` 是第五个,但**不属于环节**:它对应后端 `mapping.TRIGGER_TERMINATE`,
* 只出现在流程那一格终止挂载里(`ProcessTerminateConfig.writeback`)。画布上没有
* 「终止」这个环节,这一刻挂不到任何一环上,所以 `utils/formWriteback.ts` 的
* `WRITEBACK_TRIGGERS`(环节面板能勾的那几个)里刻意没有它。
*/
export type WritebackTrigger = 'arrive' | 'leave' | 'goBack' | 'recall'
export type WritebackTrigger = 'arrive' | 'leave' | 'goBack' | 'recall' | 'terminate'
export interface WritebackMountEntry {
code: string
@ -2004,6 +2050,13 @@ export interface FormFieldDef {
* 只读 / 可编辑 / 必填即可(口径见后端 service/formruntime.effective_perm)。
*/
hidden?: boolean
/**
* 表单设计器上的「手机上不展示」:这一格在手机的摘要与「完整单据」里都不摆,
* 值照常保存、导出、打印,环节权限与联动一律照旧——它只管手机那一屏的读法,
* 电脑上还是整张表单。给领导少摆几格系统值或内部编号,勾这个,
* 别去勾「默认隐藏」(那是整张流程都不显示)。
*/
mobileHidden?: boolean
placeholder?: string
/**
* 文本类字段(`text` / `textarea` / `richtext`)的字数上限。
@ -2536,7 +2589,72 @@ export const TABLE_COLUMN_TYPES = [
export interface FormSchema {
fields: FormFieldDef[]
layout?: { columns?: number; label_width?: number; grid?: number }
layout?: { columns?: number; label_width?: number; grid?: number; mobile?: MobileLayout }
}
/**
* 手机上这一格的摆法(口径与可选档见 utils/mobileLayout.ts)。
*
* 只有「按手机端配置展示」打开时吃这一份;没开时手机版式仍走 useFormPlan 那套
* 按类型自动归置,一张表单一个字都不动。
*/
export type MobileFieldStyle =
/** 一行:左边问的是什么,右边是答案 */
| 'row'
/** 整段:标签在上、内容摊开一整块,给事由这类长文本 */
| 'block'
/** 置顶:上到单据抬头做大字,给金额这类一眼要看到的数 */
| 'float'
/** 缩略图:附件与图片直接摆出来 */
| 'gallery'
/** 数量:附件只给一行「发票 2」,图不摆 */
| 'count'
/** 收成一行:明细给「12 条 · 合计 X」,点开才逐条 */
| 'card'
/** 逐条展开:明细直接在节里一条一段摊到底 */
| 'list'
/** 外部页面:那一整页是别人系统里的东西,手机上给一张「打开」卡片,不内嵌 */
| 'embed'
/** 配置面板里一行的设置:键是字段 key,顺序就是手机上的展示顺序。 */
export interface MobileFieldLayout {
key: string
/** 摆法;留空按字段类型给默认档 */
style?: MobileFieldStyle
/** 手机上换个短名(电脑上照旧用字段标题);留空用字段标题 */
label?: string
/**
* 这一格上不上屏——**只有「外部页面」那一格吃它**。
*
* 普通格子用的还是 ``field.mobileHidden``(与属性面板那颗同一个键,不分两家);
* 而「标签页」里那一整页外部页面不是格子,没有地方挂那颗勾,只能记在这份配置里。
*/
hidden?: boolean
}
/**
* 一张表单的手机端版式配置,存在 ``content.layout.mobile``。
*
* 存这里而不是新表:它和 ``layout.columns`` 是同一层东西——只讲"这一张表怎么摆",
* 不参与流转、不参与校验,后端 clean_formats 只按类型收字段上那几栏展现配置,
* 这一份原样存回,一行后端代码都不用动。
*
* 某一格上不上屏仍然只有 ``field.mobileHidden`` 一个判据(设计器里那颗勾选框),
* 这里不再存第二份开关,免得两处各说一遍。唯一的例外是 ``hidden``:外部页面那一格
* 不是格子,没地方挂那颗勾。
*/
export interface MobileLayout {
/**
* 总开关。没开(或整份不存在)就是原来那套自动归置:按页签/分隔条分节、
* 系统取数合并成一行、末尾留「完整单据」入口——老表单一个字都不变。
*/
enabled?: boolean
/** 那一节的标题;留空取第一个页签名,再没有就叫「表单内容」 */
title?: string
/** 要不要在末尾留「完整单据」那一屏;默认不留(要的就是只有一节) */
showFullSheet?: boolean
/** 数组顺序 = 手机上的展示顺序;没列进来的格子按表单上的顺序排在后面 */
fields?: MobileFieldLayout[]
}
/** 一张表单被哪条流程用着:默认表单或点了名的环节,后端从真实引用反查。 */
@ -2758,6 +2876,7 @@ export interface ProcessDef {
approval_config?: ProcessApproval
title_config?: ProcessTitle
serial_config?: ProcessSerialTiming
terminate_config?: ProcessTerminateConfig
open_create: boolean
order_number: number
icon: string
@ -3184,6 +3303,12 @@ export interface WorkDetail {
}[]
flow: WorkFlowMap
can_terminate: boolean
/**
* 发起人此刻按不动那颗「终止」时,后端给的那句为什么(流程那一格关掉了、
* 已过设定的窗口、当前环节关了终止钮……口径全在 `service/terminate.py`)。
* 空串表示能终止;管理员恒为空串。
*/
terminate_hint?: string
/** 停在开始环节等提交(开始环节开了第三方审批时,hold 建的单先停着不流转) */
at_begin?: boolean
/** 当前用户能不能按那颗「提交」钮(发起人或管理员) */
@ -3330,6 +3455,15 @@ export interface TaskCompletedItem {
processing_type: string
label: string
latest: boolean
/**
* 这一行是**谁**结掉的,与处理人不同时才有值。
*
* 只有强制结单才写:终止把别人手上的待办一起结掉、会签凑够票后自动结掉别人的票、
* 管理员代批。持有人那一格(`identity`)不动——那张单确实在他名下办完了,
* 他的已办列表要能看见;这一格说的是「按按钮的手不是他的手」。
*/
operator?: string
operator_name?: string
/**
* 这张单被本人处理过几次。列表按单折叠成一条(口径见后端 service/completed.py),
* 摆的是最近那一次表态,次数只在这里说,历次记录在详情审批记录里一条不少。
@ -3377,6 +3511,12 @@ export interface WorkItem {
start_time: string
finish_time: string | null
duration: number
/**
* 这一条流程有没有给发起人开「终止」。**只看结构开关**(流程那一格关没关),
* 列表按这一格决定要不要画那颗钮;「已经过了设定的窗口」这类要看单据事实的判据
* 留给详情页与引擎,免得一行列表读一遍流程定义再算一次小时数。
*/
terminate_allowed?: boolean
/** 流程监控专用:这张在途单当前压着几个超时候办;已归档的单子恒为 0。 */
expired_tasks?: number
/** 流程干预:被管理员挂起的在途单。挂起不改流程状态,所以只能单独带这几个字段。 */

View File

@ -0,0 +1,12 @@
/**
* 构建号(`YYYYMMDDHHMM`)。打包时由 vite 注入,值与那次发版用的镜像 tag 同一个。
*
* 为什么要把这么个不起眼的小东西摆到界面上:发版之后人在手机上打开,光看版式
* 很难断定「是没更新成功,还是更新了我没看出来」。这一串直接把答案写在首屏——
* 对得上 `kubectl get deploy -o jsonpath=…image` 里那个 tag,就是真的生效了。
*
* 兜底那两条:vite dev 没走构建(取到的是起服务那一刻),单元测试里 define 可能不生效。
* 都不该让页面因此报错。
*/
export const APP_BUILD: string =
typeof __OA_BUILD__ === 'string' && __OA_BUILD__ ? __OA_BUILD__ : 'dev'

View File

@ -0,0 +1,140 @@
/**
* 终止在审批记录里说的那两句话。
*
* 起因是一张真实的报销单(2026-11-04):单子走到「部门主管」,主管一次都没打开过待办,
* 发起人自己在「我发起的」里把整张单终止了。第二天来问「部门主管为什么给我终止了」——
* 因为档案里只有主管名下那一行写着「终止」,按按钮的是谁,一个字都没有。
* 这里钉的是:那一行仍然留在持有人名下(他的已办要看得见这张单),但**必须**另说一句
* 是谁按的;以及终止自己那条留痕排得出来、不拿「部门主管 → 部门主管」冒充流转。
*/
import { describe, expect, it } from 'vitest'
import type { TaskCompletedItem, WorkLogItem } from '@/types'
import { buildApprovalRecord, filterSystemLogs, forcedByName } from '@/utils/approvalRecord'
function completed(over: Partial<TaskCompletedItem>): TaskCompletedItem {
return {
id: `t${Math.random().toString(36).slice(2)}`,
task: '',
job: 'j1',
work: 'w1',
title: '张锦杰发起2026年10月差旅费报销',
process: 'p1',
process_name: '费用报销流程',
serial: 'FYBX202611030017',
activity: 'cr_dept',
activity_name: '部门主管',
current_activity_name: '',
identity: 'chenshenggang',
identity_name: '陈晟罡',
unit_name: '副总经理',
creator_person: '张锦杰',
route_name: '终止',
route_alias: '',
opinion: '流程终止',
attachments: [],
start_time: '2026-11-03 17:01:14',
completed_time: '2026-11-04 10:03:33',
duration: 61338,
processing_type: 'terminate',
label: '',
latest: true,
// 真实那一行长这样:待办挂在陈晟罡名下(他一次都没打开过),按终止的是发起人
operator: 'zhangjinjie',
operator_name: '张锦杰',
...over
} as TaskCompletedItem
}
function log(over: Partial<WorkLogItem>): WorkLogItem {
return {
id: `l${Math.random().toString(36).slice(2)}`,
work: 'w1',
from_activity_name: '部门主管',
from_activity_type: 'manual',
from_identity_name: '张锦杰',
from_person_name: '张锦杰',
from_opinion: '张锦杰 终止了流程:金额填错了',
from_time: '2026-11-04 10:03:33',
arrived_activity_name: '部门主管',
arrived_activity_type: 'manual',
arrived_time: '2026-11-04 10:03:33',
route_name: '',
type: 'terminate',
duration: 0,
...over
} as WorkLogItem
}
describe('谁按的终止', () => {
it('A1 只有操作人与待办持有人不是同一个人时才算旁注', () => {
expect(forcedByName({ identity: 'chenshenggang', operator: 'zhangjinjie', operator_name: '张锦杰' })).toBe('张锦杰')
// 没写操作人 = 本人自己办的;操作人就是持有人 = 自己终止掉自己手上那条待办
expect(forcedByName({ identity: 'chenshenggang', operator: '', operator_name: '' })).toBe('')
expect(forcedByName({ identity: 'chenshenggang', operator: 'chenshenggang', operator_name: '陈晟罡' })).toBe('')
// 老数据只有 id 没有名字快照时,至少把 id 说出来,别整个不说
expect(forcedByName({ identity: 'a', operator: 'b', operator_name: '' })).toBe('b')
})
it('A2 那一行仍旧挂在持有人名下,同时说得出是谁按的', () => {
const [entry] = buildApprovalRecord({ items: [completed({})], withSystemEvents: false })
expect(entry.kind).toBe('approval')
expect(entry.title).toBe('部门主管')
expect(entry.handler).toBe('陈晟罡')
expect(entry.unit).toBe('副总经理')
expect(entry.operatorName).toBe('张锦杰')
expect(entry.processingType).toBe('terminate')
})
it('A3 正常办完的那一步不带旁注', () => {
const [entry] = buildApprovalRecord({
items: [completed({ processing_type: 'normal', operator: '', operator_name: '', opinion: '' })]
})
expect(entry.operatorName).toBe('')
})
it('A4 自己终止掉自己手上那条待办:不给自己发一句「你被某某终止」', () => {
const [entry] = buildApprovalRecord({
items: [completed({ identity: 'zhangjinjie', identity_name: '张锦杰', operator: 'zhangjinjie', operator_name: '张锦杰' })]
})
expect(entry.operatorName).toBe('')
// 角标照旧是「终止」这一档配色:这一环毕竟没批过去
expect(entry.tone).toBe('danger')
})
})
describe('终止自己那条留痕', () => {
it('B1 排得进「全部事件」,事件名叫流程终止', () => {
const row = log({})
expect(filterSystemLogs([row])).toHaveLength(1)
const entries = buildApprovalRecord({ items: [], logs: [row], withSystemEvents: true })
const entry = entries.find((item) => item.kind === 'system')
expect(entry?.titleKey).toBe('task.logTerminated')
expect(entry?.icon).toBe('ban')
expect(entry?.text).toContain('金额填错了')
})
it('B2 不拿出发地→到达地冒充一次流转:终止整张单,两端都是停着的那一环', () => {
const entries = buildApprovalRecord({ items: [], logs: [log({})], withSystemEvents: true })
const entry = entries.find((item) => item.kind === 'system')
expect(entry?.fromName).toBe('')
expect(entry?.toName).toBe('')
})
it('B3 挂起那种照常两端都报,别把这次收口误伤到旁挂事件', () => {
const entries = buildApprovalRecord({
items: [],
logs: [log({ type: 'suspend', from_activity_name: '部门主管', arrived_activity_name: '部门主管' })],
withSystemEvents: true
})
const entry = entries.find((item) => item.kind === 'system')
expect(entry?.fromName).toBe('部门主管')
expect(entry?.toName).toBe('部门主管')
})
it('B4 不开「全部事件」时它不占审批序号:终止不是一步审批', () => {
const entries = buildApprovalRecord({ items: [completed({})], logs: [log({})], withSystemEvents: false })
expect(entries).toHaveLength(1)
expect(entries[0].step).toBe(1)
})
})

View File

@ -61,6 +61,16 @@ export interface ApprovalRecordEntry {
nextParams: Record<string, string>
/** 这一步改动过的表单字段(同环节多条记录时挂在表态那条上) */
formChanges: { key: string; label: string; before: string; after: string }[]
/**
* 这一行是**别人替他结掉的**:按按钮那只手的人名。
*
* 只在强制结单上有值(终止把还挂在别人手上的待办一起结掉那一类),与处理人
* ``identity`` 相同时留空。缺了这一格,界面就只能说「部门主管终止了这张单」,
* 而按钮的其实是坐在另一头的发起人。
*/
operatorName: string
/** 这一行原本记的处理方式(normal / terminate / auto…):旁注那句要说的是哪一种动作 */
processingType: string
/** 批注专属:谁发的、是不是当前用户自己发的、@ 了谁 */
identity: string
mine: boolean
@ -269,7 +279,8 @@ const LOG_LABEL_KEYS: Record<string, string> = {
gatePass: 'task.logGatePass',
serial: 'task.logSerial',
end: 'task.logEnded',
cancel: 'task.logCanceled'
cancel: 'task.logCanceled',
terminate: 'task.logTerminated'
}
/** 值得在审批记录里单独看一眼的引擎事件:网关、脚本、子流程、撤回,以及办结/作废 */
@ -290,7 +301,10 @@ const SYSTEM_LOG_TYPES = new Set([
'dataFix',
// 应急放行没换环节,却是一次有人签名的动作:不列出来,审批记录就缺了最该看的一段
'gatePass',
'serial'
'serial',
// 终止不是一步流转,引擎过去只把它写在被抹掉那条待办的已办行上:谁按的、为什么按,
// 审批记录里一个字都看不到。现在它自己留一条,就得排得出来。
'terminate'
])
const LOG_ICONS: Record<string, IconName> = {
@ -311,7 +325,8 @@ const LOG_ICONS: Record<string, IconName> = {
gatePass: 'key',
serial: 'tag',
end: 'checkCircle',
cancel: 'ban'
cancel: 'ban',
terminate: 'ban'
}
/**
@ -445,7 +460,21 @@ const BLANK = {
nextKey: '',
nextParams: {} as Record<string, string>,
formChanges: [],
tone: 'neutral' as RecordTone
tone: 'neutral' as RecordTone,
operatorName: '',
processingType: ''
}
/**
* 这一行是谁结掉的:与待办持有人不是同一个人时才算「替他结的」。
*
* 后端只在强制结单上写 ``operator``(见 ``engine._complete_task``),持有人那一格不动——
* 那张单确实在他名下办完了,他自己的已办列表要看得见这一行。判据与后端一句对齐:
* 操作人空、或就是持有人本人,都不算旁注。
*/
export function forcedByName(item: Pick<TaskCompletedItem, 'identity' | 'operator' | 'operator_name'>): string {
const operator = String(item.operator ?? '').trim()
if (!operator || operator === String(item.identity ?? '').trim()) return ''
return String(item.operator_name ?? '').trim() || operator
}
/**
@ -563,6 +592,8 @@ function approvalEntry(
// 系统留痕(_fetch / _quota 这类下划线键)不是人工改动:引擎已经不记了,
// 这里再挡一道,免得改之前落库的那几条老记录还在审批轨迹里冒充「改了字段」
formChanges: (item.form_changes || []).filter((change) => !String(change.key ?? '').startsWith('_')),
operatorName: forcedByName(item),
processingType: String(item.processing_type ?? ''),
identity: item.identity,
mine: false
}
@ -633,8 +664,13 @@ function skipEntry(
}
}
function systemEntry(log: WorkLogItem): ApprovalRecordEntry {
const closed = log.arrived_activity_type === 'end' || log.arrived_activity_type === 'cancel'
// 终止整张单,不是从哪儿走到哪儿:引擎那条留痕出发地与到达地都是当时停着的那一环,
// 照原样摆出来就成了「部门主管 → 部门主管」这句没人听得懂的话。谁终止的、为什么终止,
// 正文那一句已经说全了(引擎写的是「某某 终止了流程:原因」)。
const whole = log.type === 'terminate'
return {
...BLANK,
key: `system:${log.id}`,
@ -646,8 +682,8 @@ function systemEntry(log: WorkLogItem): ApprovalRecordEntry {
titleKey: LOG_LABEL_KEYS[log.type] || LOG_LABEL_KEYS[log.arrived_activity_type] || 'task.logMoved',
handler: '',
unit: '',
fromName: log.from_activity_name,
toName: log.arrived_activity_name,
fromName: whole ? '' : log.from_activity_name,
toName: whole ? '' : log.arrived_activity_name,
routeName: log.route_name,
durationSeconds: log.duration,
text: log.from_opinion,

View File

@ -986,6 +986,8 @@ function nodeSummaryLines(
fmt?: (key: string, params?: Record<string, string | number>) => string
/** 这一环是不是「流程编号在这一刻生成」的那一环;由调用方算好话术传进来。 */
serialHere?: SummaryLine | null
/** 这一环是不是「发起人过了这儿就不能终止」的那一环;同样由调用方算好话术。 */
terminateHere?: SummaryLine | null
}
): SummaryLine[] {
const labels = ctx.labels
@ -1110,6 +1112,7 @@ export function nodeSummary(
): SummaryLine[] {
const lines = nodeSummaryLines(node, ctx)
if (ctx.serialHere) lines.push(ctx.serialHere)
if (ctx.terminateHere) lines.push(ctx.terminateHere)
return lines
}

View File

@ -74,14 +74,18 @@ export const WRITEBACK_TRIGGER_LABELS: Record<string, string> = {
arrive: '到达本环节时',
leave: '本环节审批通过后',
goBack: '本环节被退回时',
recall: '本环节被撤回时'
recall: '本环节被撤回时',
// 流程终止时:只有流程上那一格终止挂载用这一刻(见 utils/terminateConfig.ts)。
// 它不在 WRITEBACK_TRIGGERS 里 —— 那一刻不挂在任何环节上,环节面板不该给选。
terminate: '流程终止时'
}
/** 写法归一(同后端 mapping.TRIGGER_ALIASES):导出件与手改 JSON 的几种拼写都算同一个时刻。 */
export const WRITEBACK_TRIGGER_ALIASES: Record<string, string> = {
arrive: 'arrive',
leave: 'leave',
goback: 'goBack', go_back: 'goBack', back: 'goBack',
recall: 'recall', retract: 'recall', reset: 'recall'
recall: 'recall', retract: 'recall', reset: 'recall',
terminate: 'terminate', terminated: 'terminate'
}
/**
* 幂等键里会补一截时刻段的只有这两个时刻。到达 / 通过那两段仍旧留空——存量报文的幂等键

View File

@ -0,0 +1,174 @@
// @vitest-environment jsdom
import { beforeAll, describe, expect, it } from 'vitest'
import { i18n } from '@/i18n'
import zh from '@/i18n/locales/zh'
import {
defaultStyleFor,
isMobileEligible,
mobileCells,
mobileEntries,
mobileFieldLabel,
mobileCount,
mobileLayoutOf,
pruneMobileLayout,
styleFor,
styleOptionsFor
} from './mobileLayout'
import type { FormFieldDef, FormSchema, MobileLayout } from '@/types'
beforeAll(() => {
i18n.global.setLocaleMessage('zh', zh)
i18n.global.locale.value = 'zh'
})
function field(over: Partial<FormFieldDef> & { key: string; type: FormFieldDef['type'] }): FormFieldDef {
return { label: over.key, ...over } as FormFieldDef
}
const FIELDS = [
field({ key: 'reason', label: '报销事由', type: 'textarea' }),
field({ key: 'sec', label: '一、基本信息', type: 'divider' }),
field({ key: 'amount', label: '报销金额', type: 'money' }),
field({ key: 'rows', label: '费用明细', type: 'table' }),
field({ key: 'invoices', label: '发票', type: 'attachment' }),
field({ key: 'gone', label: '内部编号', type: 'text', mobileHidden: true })
]
function schema(mobile?: MobileLayout): FormSchema {
return { fields: FIELDS, layout: mobile ? { columns: 12, grid: 12, mobile } : { columns: 12, grid: 12 } }
}
describe('手机端那份配置读不读得出来', () => {
it('没配、配了但开关关着,都回 null:老表单继续走自动归置', () => {
expect(mobileLayoutOf(schema())).toBeNull()
expect(mobileLayoutOf(schema({ enabled: false, fields: [{ key: 'reason' }] }))).toBeNull()
expect(mobileLayoutOf(null)).toBeNull()
expect(mobileLayoutOf(schema({ enabled: true }))).toEqual({ enabled: true })
})
it('排版件与标签页容器上不了手机屏,配置里也不列它们', () => {
expect(isMobileEligible(field({ key: 'sec', type: 'divider' }))).toBe(false)
expect(isMobileEligible(field({ key: 'note', type: 'description' }))).toBe(false)
expect(isMobileEligible(field({ key: 'host', type: 'tabs', tabs: [] }))).toBe(false)
// 外部页面那一格不再是"摆不上"的一类:它没有值,但配表的人有权给不给那张「打开」卡片
expect(isMobileEligible(field({ key: 'page', type: 'embed' }))).toBe(true)
expect(isMobileEligible(field({ key: 'amount', type: 'money' }))).toBe(true)
})
})
describe('「标签页」里那一整页外部页面也能配', () => {
const CELLS = [
field({ key: 'reason', label: '报销事由', type: 'textarea' }),
field({
key: 'tabs_host',
label: '标签页',
type: 'tabs',
tabs: [
{ key: 'tab_1', label: '费用报销基本信息' },
{ key: 'tab_2', label: '费用报销发票信息', kind: 'embed', embed: { source: 'erp-invoice' } }
]
}),
field({ key: 'page', label: '合同扫描件', type: 'embed', embed: { source: 'crm' } })
]
it('清单里多一行外部页面:键带着页签,名字用页签名', () => {
const cells = mobileCells(CELLS)
expect(cells.map((row) => row.key)).toEqual(['reason', 'page', 'tabs_host#tab_2'])
const embed = cells.find((row) => row.embed)
expect(embed?.field.type).toBe('embed')
expect(embed?.field.label).toBe('费用报销发票信息')
expect(embed?.slotKey).toBe('tabs_host#tab_2')
})
it('那一档只有「打开卡片」一种摆法,配了别的也回落这一档', () => {
const embedCell = mobileCells(CELLS).find((row) => row.embed)
expect(styleOptionsFor(embedCell!.field).map((row) => row.value)).toEqual(['embed'])
expect(styleFor(embedCell!.field, { enabled: true }, { key: 'x', style: 'block' })).toBe('embed')
expect(defaultStyleFor(embedCell!.field)).toBe('embed')
})
it('没配过也照样补在最后,配了就照配置的顺序排', () => {
const entries = mobileEntries({ enabled: true, fields: [{ key: 'tabs_host#tab_2' }, { key: 'reason' }] }, CELLS)
expect(entries.map((row) => row.key)).toEqual(['tabs_host#tab_2', 'reason', 'page'])
expect(entries.find((row) => row.embed)?.embed).toBe(true)
})
it('对账时那一页的键不算死配置,页签真删了才收掉', () => {
const stale: MobileLayout = { enabled: true, fields: [{ key: 'tabs_host#tab_2' }, { key: 'deleted' }, { key: 'reason' }] }
expect(pruneMobileLayout(stale, CELLS)?.fields?.map((row) => row.key)).toEqual(['tabs_host#tab_2', 'reason', 'page'])
})
it('那一页勾掉只记在配置里,不进格子的 mobileHidden', () => {
expect(mobileCount({ enabled: true, fields: [{ key: 'reason' }, { key: 'tabs_host#tab_2', hidden: true }] }, CELLS)).toEqual({
total: 3,
shown: 2,
hidden: 1
})
})
})
describe('配置里的顺序与摆法', () => {
const layout: MobileLayout = {
enabled: true,
fields: [
{ key: 'amount', style: 'float' },
{ key: 'rows', style: 'list' },
{ key: 'reason', style: 'block', label: '事由' },
{ key: 'invoices' }
]
}
it('清单顺序就是手机上的顺序,勾了「手机上不展示」的照样在清单上(面板要能把它打开)', () => {
expect(mobileEntries(layout, FIELDS).map((row) => row.field.key)).toEqual(['amount', 'rows', 'reason', 'invoices', 'gone'])
})
it('配置里没列的格子补在最后,不会因为没人配过就凭空消失', () => {
const partial: MobileLayout = { enabled: true, fields: [{ key: 'reason' }] }
expect(mobileEntries(partial, FIELDS).map((row) => row.field.key)).toEqual(['reason', 'amount', 'rows', 'invoices', 'gone'])
})
it('摆法照配置,类型吃不下的那一档回落默认档', () => {
expect(styleFor(FIELDS[2], layout, { key: 'amount', style: 'float' })).toBe('float')
expect(styleFor(FIELDS[3], layout, { key: 'rows', style: 'list' })).toBe('list')
// 明细没有「整段」这一档,配了也白配
expect(styleFor(FIELDS[3], layout, { key: 'rows', style: 'block' })).toBe('card')
// 事由是长文本,没配摆法时默认就给整段
expect(styleFor(FIELDS[0], layout, undefined)).toBe('block')
expect(styleFor(FIELDS[4], null, undefined)).toBe('gallery')
})
it('手机上显示的名字:配了才换,没配回字段标题', () => {
expect(mobileFieldLabel(FIELDS[0], layout, { key: 'reason', label: '事由' })).toBe('事由')
expect(mobileFieldLabel(FIELDS[0], layout, { key: 'reason' })).toBe('报销事由')
expect(mobileFieldLabel(FIELDS[0], null, undefined)).toBe('报销事由')
})
it('每格能选哪几档是类型说了算,附件不给出「置顶」,数字才给', () => {
expect(styleOptionsFor(FIELDS[4]).map((row) => row.value)).toEqual(['gallery', 'count'])
expect(styleOptionsFor(FIELDS[3]).map((row) => row.value)).toEqual(['card', 'list'])
expect(styleOptionsFor(FIELDS[2]).map((row) => row.value)).toEqual(['row', 'block', 'float'])
expect(styleOptionsFor(FIELDS[0]).map((row) => row.value)).toEqual(['row', 'block'])
expect(defaultStyleFor(FIELDS[0])).toBe('block')
})
})
describe('配置对回现在这张表', () => {
it('删掉的格子收掉,新加的格子补在最后', () => {
const stale: MobileLayout = {
enabled: true,
fields: [{ key: 'reason' }, { key: 'deleted_one' }, { key: 'amount', style: 'float' }]
}
const withNew = [...FIELDS, field({ key: 'late', label: '补录说明', type: 'text' })]
const pruned = pruneMobileLayout(stale, withNew)
expect(pruned?.fields?.map((row) => row.key)).toEqual(['reason', 'amount', 'rows', 'invoices', 'gone', 'late'])
// 补进来的只带 key,别顺手替人决定摆法
expect(pruned?.fields?.find((row) => row.key === 'amount')?.style).toBe('float')
expect(pruned?.fields?.find((row) => row.key === 'late')).toEqual({ key: 'late' })
})
it('没开这一档时原样交回,配好的顺序不因关掉而丢失', () => {
const off: MobileLayout = { enabled: false, fields: [{ key: 'reason' }] }
expect(pruneMobileLayout(off, FIELDS)).toEqual(off)
expect(pruneMobileLayout(undefined, FIELDS)).toBeUndefined()
})
})

View File

@ -0,0 +1,211 @@
/**
* 手机端表单版式的配置层:一张表单独一份,存在 ``content.layout.mobile``。
*
* 为什么要这么一层:手机版式原先完全靠"按字段类型自动归置"(`components/oa/mobile/useFormPlan.ts`),
* 配表的人只能逐格勾「手机上不展示」,摆成什么样、先摆哪一格、明细摊不摊开,全都定不了。
* 开了这一档之后手机上就只有一节——那一节摆哪些格、按什么顺序、每格怎么摆,在设计器
* 「手机端」面板里说一次,手机上照办。
*
* 三条边界,别越过去:
*
* 1. **没开就等于不存在**。`mobileLayoutOf` 只在 ``enabled`` 为真时回一份配置,其余一律 null,
* 老表单、没碰过这个面板的表单,走的是原来那套自动归置,一个像素都不该变。
* 2. **只管"摆不摆、怎么摆",不管"有没有值、能不能看"**。某一格最终上不上屏,还要过
* 环节字段权限(`hidden`)、整单默认隐藏(`field.hidden`)、逐格「手机上不展示」
* (`field.mobileHidden`)这三道闸——这一层不复制第二份开关,面板上那颗"显示"
* 写的就是 ``mobileHidden``,与设计器属性面板里那颗是同一个键。
* 3. **后端不认得它**。表单内容整份存在 ``oa_form.content``,``clean_formats`` 只按类型
* 收字段上那几栏展现配置,``layout`` 里的东西原样存回,所以加这一档没动一行后端。
*/
import { i18n } from '@/i18n'
import { embedSlotKey, isEmbedTab, isTabsField, tabEmbedField, tabsFieldOf, tabsOf } from '@/utils/tabPages'
import type { FormFieldDef, FormSchema, MobileFieldLayout, MobileFieldStyle, MobileLayout } from '@/types'
/** 置顶那几格的上限:抬头是「这单大概是什么」,摆四五个数就成报表了。 */
export const MOBILE_FLOAT_MAX = 3
/**
* 上不了手机那一屏的类型:纯排版(没有值)与容器(它自己就是分节的依据)。
* 与 useFormPlan 的 isLayoutField 同一批,只是这里连 divider 一起收——配置开了以后
* 只有一节,分隔条不再当段名用,摆上去只会多一行空白。
*
* `embed` 不在这一列:那一整页是别人系统里的东西,摆不上这一节的**值**那一栏,
* 但配表的人有权决定它在手机上给不给一张「打开」卡片(见下面 `mobileCells`)。
*/
const INELIGIBLE: string[] = ['divider', 'description', 'group', 'spacer', 'hidden', 'title']
/** 能选「置顶」的类型:只有本身就是个数的东西,做成大字才有意义。 */
const NUMERIC_TYPES = new Set(['money', 'number', 'formula', 'rate'])
const MEDIA_TYPES = new Set(['attachment', 'image'])
export function isMobileEligible(field: FormFieldDef | undefined | null): boolean {
if (!field) return false
if (isTabsField(field)) return false
return !INELIGIBLE.includes(String(field.type))
}
/**
* 手机上能摆的一格:表单上的格子,外加「标签页」里那一整页外部页面。
*
* 外部页面那一格是合成出来的(`tabPages.tabEmbedField`),它不在画布的格子上,
* 于是配置里的键得带页签才认得出是哪一页:`宿主格子key#页签key`。
*/
export interface MobileCell {
/** 配置里那一条的键:普通格子是字段 key,外部页面那一页是 `格子key#页签key` */
key: string
field: FormFieldDef
embed: boolean
/** 外部页面那一格的回写分区键,交给 EmbedFrame;普通格子为空串 */
slotKey: string
}
/** 这一张表在手机上能摆的所有格子,按表单上的顺序;外部页面那几页排在最后。 */
export function mobileCells(fields: FormFieldDef[] = []): MobileCell[] {
const cells: MobileCell[] = fields.filter(isMobileEligible).map((field) => ({
key: String(field.key ?? ''),
field,
embed: false,
slotKey: ''
}))
const host = tabsFieldOf(fields)
if (host) {
const hostKey = String(host.key ?? '')
tabsOf(host).forEach((tab) => {
if (!isEmbedTab(tab)) return
const slotKey = embedSlotKey(hostKey, String(tab.key ?? ''))
cells.push({ key: slotKey, field: tabEmbedField(host, tab), embed: true, slotKey })
})
}
return cells
}
/** 这一张表单有没有开手机端配置;没开一律回 null,让调用方走原来那套自动归置。 */
export function mobileLayoutOf(schema?: FormSchema | null): MobileLayout | null {
const mobile = schema?.layout?.mobile
return mobile && mobile.enabled ? mobile : null
}
/** 面板上那一栏的默认值:开开关时先按表单上的顺序把能上屏的格子列出来。 */
export function defaultMobileLayout(): MobileLayout {
return { enabled: true, title: '', showFullSheet: false, fields: [] }
}
/** 这一格在手机上默认怎么摆。 */
export function defaultStyleFor(field: FormFieldDef): MobileFieldStyle {
if (field.type === 'embed') return 'embed'
if (MEDIA_TYPES.has(field.type)) return 'gallery'
if (field.type === 'table') return 'card'
if (field.type === 'textarea' || field.type === 'richtext') return 'block'
return 'row'
}
/**
* 这一格能选哪几档摆法。给了清单,面板上就不会让人选出一个手机上摆不出来的组合
* (明细选「整段」、附件选「置顶」这种)。
*/
export function styleOptionsFor(field: FormFieldDef): { value: MobileFieldStyle; label: string }[] {
const label = (key: string) => i18n.global.t(`mobile.layoutStyle.${key}`)
// 外部页面只有一档:那一整页在 390px 里嵌进来就是没法看,给卡片不内嵌
if (field.type === 'embed') {
return [{ value: 'embed', label: label('embed') }]
}
if (field.type === 'table') {
return [
{ value: 'card', label: label('card') },
{ value: 'list', label: label('list') }
]
}
if (MEDIA_TYPES.has(field.type)) {
return [
{ value: 'gallery', label: label('gallery') },
{ value: 'count', label: label('count') }
]
}
if (field.type === 'signature') {
return [{ value: 'row', label: label('row') }]
}
const options = [
{ value: 'row' as MobileFieldStyle, label: label('row') },
{ value: 'block' as MobileFieldStyle, label: label('block') }
]
if (NUMERIC_TYPES.has(field.type)) options.push({ value: 'float', label: label('float') })
return options
}
/** 这一格实际生效的摆法:配置里那档 + 类型能不能吃这一档兜底。 */
export function styleFor(field: FormFieldDef, layout: MobileLayout | null, entry?: MobileFieldLayout): MobileFieldStyle {
const wanted = entry?.style ?? layout?.fields?.find((item) => item.key === field.key)?.style
if (!wanted) return defaultStyleFor(field)
// 配置是从别的表单粘过来的、或者类型换过了:这一档新类型吃不下去就回落默认档
return styleOptionsFor(field).some((item) => item.value === wanted) ? wanted : defaultStyleFor(field)
}
/** 手机上这一格的标题:配了短名用短名,否则用字段自己的。 */
export function mobileFieldLabel(field: FormFieldDef, layout: MobileLayout | null, entry?: MobileFieldLayout): string {
// 给了 entry 就以它为准:调用方手上那份就是此刻生效的那一行配置,不该再去整份里捞一遍
const wanted = entry ? entry.label : layout?.fields?.find((item) => item.key === field.key)?.label
const text = String(wanted ?? '').trim()
return text || String(field.label ?? field.key ?? '')
}
/**
* 手机上的展示顺序与逐格设置:配置里列出来的在前,按配置的顺序;
* 没列进来的(后来新加的格子)按表单上的顺序跟在后面,摆法走默认档。
*
* 为什么留这一手:配完手机端版式之后又往表单上加格子是常事,这时候新格子该出现,
* 而不是因为没人配过就凭空消失——消失更难查。
*/
export function mobileEntries(
layout: MobileLayout | null,
fields: FormFieldDef[]
): (MobileCell & { entry: MobileFieldLayout })[] {
if (!layout) return []
const byKey = new Map((layout.fields ?? []).map((item) => [String(item.key), item]))
const cells = mobileCells(fields)
const listed: (MobileCell & { entry: MobileFieldLayout })[] = []
cells.forEach((cell) => {
const entry = byKey.get(cell.key)
if (entry) listed.push({ ...cell, entry })
})
// 先按配置数组的顺序排:上面收的是"哪些格子有配置",顺序由配置那边说话
const rank = new Map((layout.fields ?? []).map((item, index) => [String(item.key), index]))
listed.sort((a, b) => (rank.get(a.key) ?? 0) - (rank.get(b.key) ?? 0))
const known = new Set(listed.map((item) => item.key))
cells.forEach((cell) => {
if (!known.has(cell.key)) listed.push({ ...cell, entry: { key: cell.key } })
})
return listed
}
/**
* 把配置对回当前这张表的格子上:删掉的格子收掉,新加的格子补在最后。
*
* 面板每次打开、每次保存前都过这一道,于是 `layout.fields` 里的 key 永远是真实存在的格子,
* 不会出现"配过的那格早删了,手机上少一行却说不出为什么"。没开配置时原样交回,
* 一份空配置也不会被写成 `{enabled:false, fields:[]}` 这种多余的东西。
*/
export function pruneMobileLayout(layout: MobileLayout | null | undefined, fields: FormFieldDef[]): MobileLayout | undefined {
// 没开配置时原样交回:关开关的人多半只是想先看一眼自动归置那版,配好的顺序得留着
if (!layout || !layout.enabled) return layout ?? undefined
const keys = mobileCells(fields).map((cell) => cell.key)
const seen = new Set<string>()
const kept: MobileFieldLayout[] = []
// 前面那行以 `]` 收尾,这里不以分号开头会被读成调用一个数组(kept 的初始化紧挨着它)
;(layout.fields ?? []).forEach((item) => {
const key = String(item.key ?? '')
if (!keys.includes(key) || seen.has(key)) return
seen.add(key)
kept.push(item)
})
keys.forEach((key) => {
if (!seen.has(key)) kept.push({ key })
})
return { ...layout, fields: kept }
}
/** 面板与统计用:这一份配置里此刻有几格是上的、几格是被勾掉的。 */
export function mobileCount(layout: MobileLayout | null, fields: FormFieldDef[]) {
const entries = mobileEntries(layout, fields)
const shown = entries.filter((item) => !(item.embed ? item.entry.hidden : item.field.mobileHidden) && !item.field.hidden)
return { total: entries.length, shown: shown.length, hidden: entries.length - shown.length }
}

View File

@ -85,6 +85,7 @@ export function groupLabelKey(group: NodeGroupKey, type: string): string {
return NODE_GROUP_LABEL_KEYS.payload
}
/** 协作开关:与环节面板上那一排复选框同一份清单(含单列的退回 / 加签)。 */
export const COLLAB_FLAG_KEYS = [
'allowGoBack',
@ -94,7 +95,11 @@ export const COLLAB_FLAG_KEYS = [
'allowComment',
'allowTransfer',
'allowRecall',
'allowPress'
'allowPress',
// 这一格以前是「配了不响」的死配置:设计器没有地方勾,后端只把它回显给界面。
// 现在引擎真认它(terminate_blocker 里那一档硬闸:单子正停在这一环时准不准终止),
// 界面才第一次有地方说话。它管的是「停在这一环的当口」,与流程那一格的窗口是两件事。
'allowTerminate'
] as const
export interface GroupDigest {

View File

@ -0,0 +1,75 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { computed, ref } from 'vue'
import { createPinia, setActivePinia } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import type { User } from '@/types'
// 落地页这一条判据只看屏幕宽度,所以把总闸做成开关,不去伪造 matchMedia
const phoneShell = ref(false)
vi.mock('@/composables/useMobileShell', () => ({
useMobileShell: () => ({ phoneShell: computed(() => phoneShell.value) })
}))
const { landingPath, safeRedirect } = await import('@/utils/returnPath')
/** 生产上「普通员工」那一档的真实形状:139 人挂在这,有 work:todo,偏偏没有 work:workbench。 */
const STAFF = ['portal:home', 'work:todo', 'work:profile', 'work:read']
const WITH_WORKBENCH = [...STAFF, 'work:workbench']
function signIn(permissions: string[]) {
setActivePinia(createPinia())
useAuthStore().$patch({
user: { id: 'u1', account: 'staff', display_name: '员工', permissions } as unknown as User,
token: 'token'
} as never)
}
beforeEach(() => {
phoneShell.value = false
signIn(WITH_WORKBENCH)
})
describe('打开系统第一屏落哪儿', () => {
it('桌面上还是门户首页,手机上有工作台就落那五张小卡片', () => {
expect(landingPath()).toBe('/home')
phoneShell.value = true
expect(landingPath()).toBe('/workbench')
})
it('手机上没有 work:workbench 就落待办那张卡片流,不退回门户那一屏', () => {
signIn(STAFF)
phoneShell.value = true
expect(landingPath()).toBe('/todo')
// 桌面不受这件事影响:门户照旧排第一
phoneShell.value = false
expect(landingPath()).toBe('/home')
})
it('连待办都没有就再往后退一格:我的 → 门户', () => {
phoneShell.value = true
signIn(['portal:home', 'work:profile'])
expect(landingPath()).toBe('/profile')
signIn([])
expect(landingPath()).toBe('/home')
})
it('免登与登录没带 redirect 时也按这个走(safeRedirect 的兜底就是它)', () => {
expect(safeRedirect('')).toBe('/home')
phoneShell.value = true
expect(safeRedirect(undefined)).toBe('/workbench')
signIn(STAFF)
expect(safeRedirect('')).toBe('/todo')
})
it('带了站内 redirect 就回去原页,屏幕宽度不插手', () => {
phoneShell.value = true
expect(safeRedirect('/todo/task-1')).toBe('/todo/task-1')
})
it('站外地址一律不认:手机上回落到卡片那一屏,而不是被带出系统', () => {
phoneShell.value = true
expect(safeRedirect('//evil.com')).toBe('/workbench')
expect(safeRedirect('/\\evil.com')).toBe('/workbench')
})
})

View File

@ -7,6 +7,8 @@
* 刷新后仍然在,所以直达或刷新详情页时用它的 back 补一次,两条来源取先命中的。
*/
import { ref, type Ref } from 'vue'
import { useMobileShell } from '@/composables/useMobileShell'
import { useAuthStore } from '@/stores/auth'
import type { RouteLocationNormalized } from 'vue-router'
/** 只存"上一条站内地址",返回按钮一次只用一个。 */
@ -24,12 +26,47 @@ function fromBrowserState(): string {
return isInternal(back) ? back : ''
}
/** 一张表:从前往后问「这一条他进得去吗」,第一个命中的就是第一屏。 */
type LandingStep = readonly [permission: string, path: string]
/**
* 手机上:工作台(那五张小卡片)→ 待办 → 我的 → 门户。
*
* 从企微点进来的人是来批单子的,先给他看一轮新闻再自己摸进列表,等于手机版式白做,
* 所以门户这一档在手机上排到最后。工作台排第一却不一定是他的——生产上 139 个人挂在
* 「普通员工」这个角色上,那一档有 work:todo 却没 work:workbench,这类人直接落
* 待办那张卡片流(手机版式),别退回门户那一屏桌面版面。
*/
const PHONE_LANDING: readonly LandingStep[] = [
['work:workbench', '/workbench'],
['work:todo', '/todo'],
['work:profile', '/profile'],
['portal:home', '/home']
]
/** 桌面:门户第一,与改造之前一模一样。 */
const DESKTOP_LANDING: readonly LandingStep[] = [
['portal:home', '/home'],
['work:workbench', '/workbench'],
['work:todo', '/todo'],
['work:profile', '/profile']
]
/**
* 打开系统第一屏落哪儿:先按设备挑表,再按权限挑那一条真进得去的。
*
* 门户没丢:抽屉侧栏里 `/home` 那一条还在(`components/layout/AppLayout` 的抽屉),
* 只是手机不再拿它当第一屏。一张表都没命中(权限少到极点)也回 `/home`,
* 让路由守卫去把人送去登录页,这里不自己发明去处。
*/
export function landingPath(): string {
const authStore = useAuthStore()
const steps = useMobileShell().phoneShell.value ? PHONE_LANDING : DESKTOP_LANDING
return steps.find(([code]) => authStore.can(code))?.[1] ?? '/home'
}
/**
* 登录或免登成功之后回哪一页:地址栏里的 `redirect` 谁都能改,只放行站内路径。
*
* `//evil.com` 与 `/\\evil.com` 这两种写法浏览器会当成另一台主机,一律回落到兜底页。
*/
export function safeRedirect(path: unknown, fallback = '/home'): string {
export function safeRedirect(path: unknown, fallback = landingPath()): string {
const value = typeof path === 'string' ? path.trim() : ''
return /^\/(?!\/|\\)/.test(value) ? value : fallback
}

View File

@ -0,0 +1,172 @@
/**
* 「终止」那一格的前端口径。
*
* 这一格是**规矩**而不是装饰:界面写着「能终止」而引擎抛一句没见过的话,或者配置
* 存成了「走到部门主管之后不许」而跑起来仍旧随时能终止,都属于同一类最难查的账。
* 所以钉死四件事:读回来的形状、保存前的把关、写回那半的落库形状(别把别的时刻
* 一起洗掉)、以及三种「配了不响」当场有没有点名。后端那一份对住在
* backend/scripts/check_terminate_control.py 的 A 组。
*/
import { describe, expect, it } from 'vitest'
import type { IntegrationTemplate, WritebackMount } from '@/types'
import {
TERMINATE_UNTILS,
defaultTerminateConfig,
normaliseTerminateConfig,
terminateConfigured,
terminateMountCodes,
terminateMountWarnings,
terminateMountWithCodes,
terminateNeedsNode,
terminateProblemKey,
terminateSummaryKey
} from '@/utils/terminateConfig'
describe('读回来的形状', () => {
it('A1 空配置就是出厂口径:开着、随时能终止、没挂写回', () => {
expect(normaliseTerminateConfig(undefined)).toEqual(defaultTerminateConfig())
expect(normaliseTerminateConfig({})).toEqual(defaultTerminateConfig())
expect(terminateConfigured({})).toBe(false)
})
it('A2 认不出的窗口回到默认,不把整条流程的终止卡死', () => {
const config = normaliseTerminateConfig({ until: 'forever' as never, untilHours: 12 })
expect(config.until).toBe('always')
expect(config.untilHours).toBe(0)
})
it('A3 allowStarter 只认明确的 false:没写与写成假字符串都还是开着', () => {
expect(normaliseTerminateConfig({}).allowStarter).toBe(true)
expect(normaliseTerminateConfig({ allowStarter: false }).allowStarter).toBe(false)
expect(terminateSummaryKey({ allowStarter: false })).toBe('process.terminateSummary.off')
})
it('A4 换档之后不留孤儿值:环节 id 与小时数只在自己那一档里活着', () => {
const both = { until: 'beforeActivity', untilActivity: 'cr_dept', untilHours: 24 } as never
expect(normaliseTerminateConfig(both).untilHours).toBe(0)
const hours = { until: 'withinHours', untilActivity: 'cr_dept', untilHours: 24 } as never
expect(normaliseTerminateConfig(hours).untilActivity).toBe('')
// 切回「随时都能」两样都收掉,免得留下一格看上去还在挡的假配置
expect(normaliseTerminateConfig({ ...both, until: 'always' } as never)).toEqual(defaultTerminateConfig())
})
it('A5 窗口写歪的小时数不认:0 与负数都当没填', () => {
expect(normaliseTerminateConfig({ until: 'withinHours', untilHours: 0 }).untilHours).toBe(0)
expect(normaliseTerminateConfig({ until: 'withinHours', untilHours: -5 }).untilHours).toBe(0)
expect(normaliseTerminateConfig({ until: 'withinHours', untilHours: '36' }).untilHours).toBe(36)
})
})
describe('保存前的把关', () => {
it('B1 四档窗口各自该问的那一句', () => {
expect(terminateProblemKey({ until: 'beforeActivity' })).toBe('process.terminateNodeRequired')
expect(terminateProblemKey({ until: 'beforeActivity', untilActivity: 'cr_dept' })).toBe('')
expect(terminateProblemKey({ until: 'withinHours' })).toBe('process.terminateHoursRequired')
expect(terminateProblemKey({ until: 'withinHours', untilHours: 24 })).toBe('')
expect(terminateProblemKey({ until: 'always' })).toBe('')
})
it('B2 指着的环节已经不在画布上了,当场说', () => {
expect(
terminateProblemKey({ until: 'beforeActivity', untilActivity: 'gone' }, ['cr_dept', 'cr_end'])
).toBe('process.terminateNodeMissing')
// 清单还没拿到(空数组)时不判这一条,跟编号那一格同一分寸
expect(terminateProblemKey({ until: 'beforeActivity', untilActivity: 'gone' }, [])).toBe('')
})
it('B3 小时数超过一年算配错,不等后端退回才知道', () => {
expect(
terminateProblemKey({ until: 'withinHours', untilHours: 999999 }).startsWith('process.terminateHours')
).toBe(true)
})
it('B4 摘要:只有出厂口径不占一行,需要点环节的那一档说得出要点名', () => {
expect(terminateSummaryKey({})).toBe('')
expect(terminateSummaryKey({ until: 'notHandled' })).toBe('process.terminateSummary.notHandled')
expect(terminateSummaryKey({ until: 'withinHours', untilHours: 24 })).toBe(
'process.terminateSummary.withinHours'
)
expect(terminateNeedsNode({ until: 'beforeActivity', untilActivity: 'cr_dept' })).toBe(true)
expect(terminateNeedsNode({ until: 'withinHours', untilHours: 24 })).toBe(false)
expect(TERMINATE_UNTILS).toHaveLength(4)
})
})
describe('写回那一半的落库形状', () => {
it('C1 勾了模板才是一条 terminate 时刻的规则;一个都没勾等于摘掉整段', () => {
const mount = terminateMountWithCodes({}, ['reimb_chct'])
expect(mount).toEqual({ integrations: ['reimb_chct'], trigger: 'terminate' })
expect(terminateMountCodes(mount)).toEqual(['reimb_chct'])
expect(terminateMountWithCodes(mount, [])).toBeNull()
})
it('C2 没写时刻的存量环节规则按 arrive 读,绝不会被当成终止那一格', () => {
const legacy: WritebackMount = { integrations: ['a'], trigger: undefined }
expect(terminateMountCodes(legacy)).toEqual([])
expect(terminateMountCodes({ integrations: ['b'], trigger: 'terminated' as never })).toEqual(['b'])
})
it('C3 改勾选不许把别的时刻一起洗掉,也不许把已经勾选项上的条件抹平', () => {
const base = {
blocks: [
{ integrations: ['arrive_tpl'], trigger: 'arrive' },
{ integrations: [{ code: 'term_tpl', fields: ['amount'] }], trigger: 'terminate', when: { rules: [{ field: 'total', op: 'gt', value: 100 }], group: 'and' } }
]
} as unknown as WritebackMount
expect(terminateMountCodes(base)).toEqual(['term_tpl'])
const next = terminateMountWithCodes(base, ['term_tpl', 'another']) as WritebackMount
const blocks = next.blocks ?? []
expect(blocks).toHaveLength(2)
expect(blocks.map((block) => block.trigger)).toEqual(['arrive', 'terminate'])
// 「要发的字段」与整批条件原样留着,新勾那一项仍旧是光一个编码
expect(blocks[1].integrations).toEqual([{ code: 'term_tpl', fields: ['amount'] }, 'another'])
expect(blocks[1].when).toBeTruthy()
// 摘干净终止那几条之后,arrive 的规则一条不少
const only = terminateMountWithCodes(base, ['another']) as WritebackMount
expect(only.blocks?.map((block) => block.trigger)).toEqual(['arrive', 'terminate'])
})
it('C4 只有一条规则时仍旧平铺,不为了这次改动整体换形状', () => {
const mount = terminateMountWithCodes(terminateMountWithCodes({}, ['x']) as WritebackMount, ['x', 'y'])
expect(mount).toEqual({ integrations: ['x', 'y'], trigger: 'terminate' })
})
})
describe('三种配了不响', () => {
const tpl = (over: Partial<IntegrationTemplate>): IntegrationTemplate =>
({ code: 'c', name: '模板 C', source: 'reimb', enabled: true, ...over }) as IntegrationTemplate
it('D1 模板自己已勾终止:那一刻会各发一条,得当面问一句是不是重复', () => {
expect(terminateMountWarnings(['c'], [tpl({ triggerEvents: ['terminated'] })])).toEqual([
{ key: 'process.terminateWarnOverlap', params: { name: '模板 C' } }
])
})
it('D2 老那一格 triggerEvent 也算自己会发', () => {
expect(
terminateMountWarnings(['c'], [tpl({ triggerEvent: 'terminated' as never })]).map((item) => item.key)
).toContain('process.terminateWarnOverlap')
})
it('D3 停用与绑错表单各自点一次名', () => {
const warnings = terminateMountWarnings(
['c', 'd'],
[tpl({ code: 'c', name: '停的', enabled: false }), tpl({ code: 'd', name: '别家的', bizForm: 'f2' })],
'f1'
)
expect(warnings).toEqual([
{ key: 'process.terminateWarnDisabled', params: { name: '停的' } },
{ key: 'process.terminateWarnForm', params: { name: '别家的' } }
])
})
it('D4 没绑表单、或绑的就是这张表单,都不啰嗦;清单里查不到的模板也不猜', () => {
expect(terminateMountWarnings(['c'], [tpl({ bizForm: 'f1' })], 'f1')).toEqual([])
expect(terminateMountWarnings(['c'], [tpl({})], 'f1')).toEqual([])
expect(terminateMountWarnings(['ghost'], [tpl({})], 'f1')).toEqual([])
})
it('D5 配过终止规矩的判据含写回那一格:只勾模板也算配过,摘要不能装看不见', () => {
expect(terminateConfigured({ writeback: { integrations: ['c'], trigger: 'terminate' } })).toBe(true)
})
})

View File

@ -0,0 +1,196 @@
/**
* 「发起人到什么时候为止还能终止这张单」的前端口径。
*
* 真正挡人的是后端:判据在 `service/terminate.py`,落在引擎 `terminate_blocker`,
* 详情页那句提示和引擎抛出的那句同源。这里只管设计器那三件事——把库里读来的配置
* 收成干净形状、保存前把关一次、算一句给人看的摘要,键名与后端一字不差:
* ``allowStarter`` / ``until`` / ``untilActivity`` / ``untilHours`` / ``writeback``。
*
* 为什么这一格长在流程上而不是环节上:终止是**整张单**的动作,不是当前那一环的表态,
* 画布上也没有「终止」这个环节可以挂。环节上那一格 `allowTerminate` 管的是另一件事
* ——「单子正停在这一环的时候准不准终止」,两处各说各的,互不覆盖。
*/
import type {
IntegrationTemplate,
ProcessTerminateConfig,
ProcessTerminateUntil,
WritebackMount,
WritebackMountBlock,
WritebackMountEntry
} from '@/types'
import { mountBlocks, mountEntries, mountEntryList, mountShape, mountTriggers, terminalEventsOf } from './formWriteback'
/** 流程那一格固定的触发时刻,同后端 ``mapping.TRIGGER_TERMINATE``。 */
export const TERMINATE_TRIGGER = 'terminate'
/** 四档窗口;顺序就是设计器里那一列的顺序。 */
export const TERMINATE_UNTILS: ProcessTerminateUntil[] = ['always', 'notHandled', 'beforeActivity', 'withinHours']
/** 小时档的范围,同后端 ``HOURS_MIN`` / ``HOURS_MAX``(上限是整整一年)。 */
export const TERMINATE_HOURS_MIN = 1
export const TERMINATE_HOURS_MAX = 24 * 365
/** 出厂口径:开着、随时能终止、没挂写回——与这份配置存在之前一字不差。 */
export function defaultTerminateConfig(): Required<ProcessTerminateConfig> {
return { allowStarter: true, until: 'always', untilActivity: '', untilHours: 0, writeback: {} }
}
/** 库里/界面上那份配置的真实形状:认不出的值回到默认,不猜。 */
export function normaliseTerminateConfig(raw?: ProcessTerminateConfig | null): Required<ProcessTerminateConfig> {
const until = String(raw?.until ?? '') as ProcessTerminateUntil
const hours = Number(raw?.untilHours ?? 0)
const writeback = raw?.writeback
return {
// 缺键 = 没配过 = 允许;只有明确写成 false 才算关掉
allowStarter: raw?.allowStarter !== false,
until: TERMINATE_UNTILS.includes(until) ? until : 'always',
// 窗口换档之后不留孤儿值:切成「有人办理之后」还挂着上一个环节 id,
// 看上去像还在按环节挡,其实那句规矩早就不生效了
untilActivity: until === 'beforeActivity' ? String(raw?.untilActivity ?? '').trim() : '',
untilHours:
until === 'withinHours' && Number.isFinite(hours) && hours >= TERMINATE_HOURS_MIN
? Math.min(Math.floor(hours), TERMINATE_HOURS_MAX * 4)
: 0,
writeback: writeback && typeof writeback === 'object' ? writeback : {}
}
}
/** 这条流程算不算「配过」终止规矩:出厂那一份算没配(摘要与体检都按这一格说话)。 */
export function terminateConfigured(raw?: ProcessTerminateConfig | null): boolean {
const config = normaliseTerminateConfig(raw)
return (
!config.allowStarter ||
config.until !== 'always' ||
terminateMountCodes(config.writeback).length > 0
)
}
/**
* 保存前的把关,返回 i18n 文案 key(没问题时空串),同后端 ``terminate_service.problems``
* 那一把尺子。环节清单由调用方给(画布上那份还没保存的也算数)——环节 id 是每条流程
* 自己的主键,复制流程、恢复版本都会换掉它,指着一条已经不存在的环节等于白配。
*/
export function terminateProblemKey(
raw: ProcessTerminateConfig | null | undefined,
knownActivityIds: string[] = []
): string {
const config = normaliseTerminateConfig(raw)
if (config.until === 'beforeActivity') {
if (!config.untilActivity) return 'process.terminateNodeRequired'
if (knownActivityIds.length && !knownActivityIds.includes(config.untilActivity)) {
return 'process.terminateNodeMissing'
}
}
if (config.until === 'withinHours') {
if (!config.untilHours) return 'process.terminateHoursRequired'
if (config.untilHours > TERMINATE_HOURS_MAX) return 'process.terminateHoursTooLarge'
}
return ''
}
/** 面板收起时也看得见的摘要:返回文案 key,环节名由调用方拼在后面。 */
export function terminateSummaryKey(raw?: ProcessTerminateConfig | null): string {
const config = normaliseTerminateConfig(raw)
if (!config.allowStarter) return 'process.terminateSummary.off'
if (config.until === 'notHandled') return 'process.terminateSummary.notHandled'
if (config.until === 'beforeActivity') return 'process.terminateSummary.beforeActivity'
if (config.until === 'withinHours') return 'process.terminateSummary.withinHours'
return ''
}
/** 摘要后面那句环节名;只有「按环节挡」那一档需要。 */
export function terminateNeedsNode(raw?: ProcessTerminateConfig | null): boolean {
return normaliseTerminateConfig(raw).until === 'beforeActivity'
}
/** 终止那一刻点名的模板编码:把所有「时刻含 terminate」的规则并起来。 */
export function terminateMountCodes(mount?: WritebackMount | null): string[] {
const codes: string[] = []
mountBlocks(mount).forEach((block) => {
if (!mountTriggers(block).includes(TERMINATE_TRIGGER)) return
mountEntries(block).forEach((entry) => codes.push(entry.code))
})
return Array.from(new Set(codes.filter(Boolean)))
}
/**
* 改完勾选之后的挂载。两条账要算清楚:
*
* 1. **别的时刻的规则原样留着**。这一格只改终止那一刻,谁在导出件里手写了一条
* 「到达时发给 A」,不该因为有人在终止那一格里多勾了一个模板就消失。
* 2. **已勾选项上那一份条件与「要发的字段」保住**。勾掉再勾回来,不该被抹平成一个光编码。
*
* 出现好几条终止规则时(界面写不出这种,只可能来自手改 JSON 或别的工具)并成一条:
* 同一个时刻、各有各的条件,摆在界面上就是一份看不懂的账,不如合成一条明的。
*/
/**
* 这一格到底配过没有:没配过就当一条规则都没有。
*
* ``mountBlocks`` 认「给个对象就是一条规则」,而这一格的空态是 ``{}``(后端 clean 出来的
* 默认值)。照原样递过去会被读成一条「空模板 + 到达时」的幽灵规则,改完勾选就凭空多一条
* 谁都没配过的规则出来。所以先问一句:有 integrations 才算数。
*/
function mountedBlocks(mount?: WritebackMount | null): WritebackMountBlock[] {
if (!mount) return []
const filled = (block?: WritebackMountBlock | null) => Boolean(block && Array.isArray(block.integrations) && block.integrations.length)
const hasRules = Array.isArray(mount.blocks) ? mount.blocks.some(filled) : filled(mount)
return hasRules ? mountBlocks(mount) : []
}
export function terminateMountWithCodes(
mount: WritebackMount | null | undefined,
codes: string[]
): WritebackMount | null {
const blocks = mountedBlocks(mount)
const picked = Array.from(new Set(codes.map((code) => String(code ?? '').trim()).filter(Boolean)))
const isTerminate = (block: WritebackMountBlock) => mountTriggers(block).includes(TERMINATE_TRIGGER)
const others = blocks.filter((block) => !isTerminate(block))
const own = blocks.filter(isTerminate)
if (!picked.length) return mountShape(others)
const known = new Map<string, WritebackMountEntry>()
own.forEach((block) => {
mountEntries(block).forEach((entry) => {
if (!known.has(entry.code)) known.set(entry.code, entry)
})
})
const entries: WritebackMountEntry[] = picked.map((code) => known.get(code) ?? { code })
const block: WritebackMountBlock = {
...(own[0] ?? {}),
integrations: mountEntryList(entries),
trigger: TERMINATE_TRIGGER
}
return mountShape([...others, block])
}
/**
* 这几个模板在终止那一刻会不会真发出去:三种「配了不响」当场点名。
*
* 后端保存时只查得到「模板还存在吗」(``design.mount_code_problems``),这三样它都判不着:
* 模板自己已经勾了终止(那一刻会各发一条,幂等键不同、互不吞并)、模板被停用、
* 模板绑的是另一张表单(终止入队时按 ``biz_form`` 对不上,一条都不发)。
* 都是配的人当场看不出来、要等一张单终止掉才发现的事,就在面板里说清楚。
*/
export function terminateMountWarnings(
codes: string[],
templates: IntegrationTemplate[],
formId = ''
): { key: string; params: Record<string, string> }[] {
const out: { key: string; params: Record<string, string> }[] = []
codes.forEach((code) => {
const template = templates.find((item) => item.code === code)
if (!template) return
const name = template.name || code
if (terminalEventsOf(template).includes('terminated')) {
out.push({ key: 'process.terminateWarnOverlap', params: { name } })
}
if (template.enabled === false) {
out.push({ key: 'process.terminateWarnDisabled', params: { name } })
}
if (formId && template.bizForm && template.bizForm !== formId) {
out.push({ key: 'process.terminateWarnForm', params: { name } })
}
})
return out
}

View File

@ -121,6 +121,7 @@ import type { HubPublicSettings } from '@/types'
import { useAuthStore } from '@/stores/auth'
import { useAppStore } from '@/stores/app'
import { safeRedirect } from '@/utils/returnPath'
import { useMobileShell } from '@/composables/useMobileShell'
import { errorMessage } from '@/utils/oa'
const { t } = useI18n()
@ -128,6 +129,7 @@ const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const appStore = useAppStore()
const { isPhone } = useMobileShell()
const account = ref('')
const password = ref('')
@ -181,7 +183,8 @@ async function submit() {
captcha_id: captcha.value?.captcha_id || '',
captcha_answer: captchaAnswer.value.trim()
})
appStore.success(t('auth.loginSuccess'))
// 手机上这一句没必要:登录完紧接着就是整屏换页,红绿条只会盖在刚出来的列表上
if (!isPhone) appStore.success(t('auth.loginSuccess'))
await router.replace(safeRedirect(route.query.redirect))
} catch (error) {
appStore.error(errorMessage(error))

View File

@ -0,0 +1,171 @@
// @vitest-environment jsdom
/**
* 「我发起的」列表上那颗终止钮。
*
* 生产上那一声「部门主管为什么给我终止了」,手就是在这张列表上按下去的:以前只要
* ``status === 'running'`` 就画一颗钮,什么流程都不问。现在看后端给的
* ``terminate_allowed``(只看流程那一格关没关,判据在 ``service/terminate.py``),
* 关掉就整颗不出现。顺带钉住终止原因必填——没写一句就不许确认。
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { computed, ref } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { createMemoryHistory, createRouter } from 'vue-router'
import { createI18n } from 'vue-i18n'
import zh from '@/i18n/locales/zh'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
import CreatedListView from './CreatedListView.vue'
import type { WorkItem } from '@/types'
const api = vi.hoisted(() => ({ listCreated: vi.fn(), listProcesses: vi.fn(), terminateJob: vi.fn(), deleteJob: vi.fn() }))
vi.mock('@/api', () => ({
designAPI: { listProcesses: api.listProcesses },
workAPI: {
listCreated: api.listCreated,
terminateJob: api.terminateJob,
deleteJob: api.deleteJob,
listComments: vi.fn()
}
}))
const phoneShell = ref(false)
vi.mock('@/composables/useMobileShell', () => ({
useMobileShell: () => ({ phoneShell: computed(() => phoneShell.value) }),
useChromeless: () => ({ chromeless: computed(() => false) })
}))
function row(over: Partial<WorkItem>): WorkItem {
return {
id: `w-${over.job}`,
job: `j-${over.serial}`,
serial: '',
title: '张锦杰发起2026年10月差旅费报销',
status: 'running',
process: 'p-expense',
process_name: '费用报销流程',
category_name: '财务',
creator_person: '张锦杰',
creator_identity_name: 'zhangjinjie',
creator_unit_name: '云智产品事业部',
current_activity_names: '部门主管',
manual_identity_text: '',
start_time: '2026-11-03 16:57:38',
finish_time: null,
duration: 0,
terminate_allowed: true,
...over
} as WorkItem
}
function rows(): WorkItem[] {
return [
// 流程没动过这一格:老行为,钮照旧在(后端缺字段时也按允许算)
row({ job: 'j-1', serial: 'FYBX202611030017' }),
// 那一格关掉了:整颗钮不出现
row({ job: 'j-2', serial: 'FYBX202611030018', terminate_allowed: false }),
// 显式允许
row({ job: 'j-3', serial: 'FYBX202611030019', terminate_allowed: true }),
// 已经归档的行本来就没有终止钮,别拿它凑数
row({ job: 'j-4', serial: 'FYBX202611030020', status: 'terminated', finish_time: '2026-11-04 10:03:33' })
]
}
async function open(list: WorkItem[]) {
api.listCreated.mockResolvedValue({ items: list, total: list.length, page: 1, page_size: 20, pages: 1 } as never)
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/created', name: 'my-created', component: CreatedListView },
{ path: '/work/:job', name: 'work-detail', component: { template: '<div />' } }
]
})
await router.push('/created')
await router.isReady()
const wrapper = mount(CreatedListView, {
attachTo: document.body,
global: {
plugins: [createPinia(), router, createI18n({ legacy: false, locale: 'zh', messages: { zh } })],
// 弹窗默认 teleport 到 body,桩掉它才留在这棵子树里,断言不必去翻全局 DOM
stubs: { Teleport: true, teleport: true }
}
})
await flushPromises()
return wrapper
}
/** 行操作里那颗「终止流程」;DataTable 这一版不是 <table>,按文字认。 */
function terminateButtons(wrapper: Awaited<ReturnType<typeof open>>) {
return wrapper.findAll('button').filter((node) => node.text().trim() === '终止流程')
}
/** 此刻开着的那只弹窗(这一页有删除与终止两只,按 show 挑才认得出是哪一只)。 */
function openDialog(wrapper: Awaited<ReturnType<typeof open>>) {
const dialog = wrapper.findAllComponents(ConfirmDialog).find((node) => node.props('show') === true)
expect(dialog, '终止弹窗没有打开').toBeTruthy()
return dialog!
}
/** 这颗钮长在哪一行上:往上找到第一个只包住一张单的那个容器,读它的单号。 */
function serialOfTerminateButton(node: { element: Element }): string {
let current: HTMLElement | null = node.element as HTMLElement
while (current && !/FYBX\d+/.test(current.textContent ?? '')) current = current.parentElement
return (current?.textContent ?? '').match(/FYBX\d+/)?.[0] ?? ''
}
beforeAll(() => {
window.matchMedia = ((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn()
})) as unknown as typeof window.matchMedia
})
beforeEach(() => {
document.body.innerHTML = ''
setActivePinia(createPinia())
api.listProcesses.mockResolvedValue([] as never)
api.terminateJob.mockResolvedValue({} as never)
phoneShell.value = false
})
describe('我发起的:终止那颗钮', () => {
it('A1 只有没被关掉的行才画终止钮', async () => {
const wrapper = await open(rows())
const buttons = terminateButtons(wrapper)
expect(buttons).toHaveLength(2)
// 该有的一颗不少、不该有的一颗不多:关掉那一格与已经归档的那两行都不许冒出来
expect(buttons.map(serialOfTerminateButton)).toEqual(['FYBX202611030017', 'FYBX202611030019'])
})
it('A2 原因没写就不许确认,写了才送得出去', async () => {
const wrapper = await open(rows())
await terminateButtons(wrapper)[0].trigger('click')
await flushPromises()
expect(openDialog(wrapper).props('confirmDisabled')).toBe(true)
await wrapper.find('textarea').setValue('金额填错了,重发一张')
await flushPromises()
expect(openDialog(wrapper).props('confirmDisabled')).toBe(false)
await openDialog(wrapper).vm.$emit('confirm')
await flushPromises()
expect(api.terminateJob).toHaveBeenCalledWith('j-1', '金额填错了,重发一张')
})
it('A3 弹窗里就写明白这句会进档案,不是白填', async () => {
const wrapper = await open(rows())
await terminateButtons(wrapper)[0].trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('终止原因')
expect(wrapper.text()).toContain('请写一句为什么终止')
})
})

View File

@ -1,10 +1,28 @@
<template>
<TablePageLayout>
<!-- 我发起的在手机上也是卡片:这张单现在停在谁手里,比它属于哪个分类更有用。 -->
<MobileCardList
v-if="phoneShell"
v-model:keyword="params.keyword"
:title="t('nav.myCreated')"
:rows="cards"
:loading="loading"
:finished="finished"
:total="pagination.total"
:show-expired="false"
:empty-hint="t('common.noData')"
@update:keyword="debouncedReload"
@refresh="reload"
@load-more="loadMore"
@open="openById"
/>
<TablePageLayout v-else>
<template #actions>
<div class="page-header mb-0 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 class="page-title">{{ t('nav.myCreated') }}</h2>
<p class="page-description">{{ t('common.total', { count: pagination.total }) }}</p>
<p class="page-description">
{{ t('common.total', { count: pagination.total }) }}
</p>
</div>
<div class="flex items-center gap-2">
<ExportButton kind="works" :query="exportQuery" :name="t('nav.myCreated')" />
@ -54,7 +72,9 @@
>
<template #cell-title="{ row }">
<div class="min-w-[220px]">
<p class="font-medium text-gray-900 dark:text-dark-100">{{ row.title }}</p>
<p class="font-medium text-gray-900 dark:text-dark-100">
{{ row.title }}
</p>
<p class="mt-0.5 text-xs text-gray-400">{{ row.serial }}</p>
</div>
</template>
@ -86,7 +106,9 @@
{{ t('work.recreate') }}
</button>
<!-- 还没发起流转的单(停在开始环节)给「删除」而不是「终止」:这张单没进过
任何人的办理,删掉就是把它扔回纸篓;已经走到别人手上的单才需要终止留痕 -->
任何人的办理,删掉就是把它扔回纸篓;已经走到别人手上的单才需要终止留痕。
流程那一格关掉发起人终止时这颗钮压根不出现(terminate_allowed 只看结构开关,
「已经过了窗口」那种要看单据事实的判据归详情页与引擎管,见 service/terminate.py) -->
<button
v-if="row.status === 'running' && row.activity_type === 'begin'"
type="button"
@ -98,7 +120,7 @@
{{ t('common.delete') }}
</button>
<button
v-else-if="row.status === 'running'"
v-else-if="row.status === 'running' && row.terminate_allowed !== false"
type="button"
class="btn btn-ghost btn-sm text-red-600"
@click.stop="askTerminate(row)"
@ -134,17 +156,20 @@
@cancel="pendingDelete = null"
/>
<ConfirmDialog
:show="confirmShow"
:title="t('task.terminate')"
:message="t('task.terminateConfirm')"
danger
:confirm-disabled="!terminateOpinion.trim()"
@confirm="confirmTerminate"
@cancel="closeTerminate"
>
<div>
<label class="input-label">{{ t('task.terminateReason') }}</label>
<TextArea v-model="terminateOpinion" :rows="3" :placeholder="t('task.terminateReasonPlaceholder')" />
<p class="mt-1 text-xs text-gray-400">{{ t('task.terminateReasonRequired') }}</p>
</div>
</ConfirmDialog>
</template>
@ -154,6 +179,10 @@ import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import TablePageLayout from '@/components/layout/TablePageLayout.vue'
import MobileCardList from '@/components/oa/mobile/MobileCardList.vue'
import type { MobileCardRow } from '@/components/oa/mobile/MobileCardList.vue'
import { useMobileFeed } from '@/composables/useMobileFeed'
import { useMobileShell } from '@/composables/useMobileShell'
import DataTable from '@/components/common/DataTable.vue'
import Pagination from '@/components/common/Pagination.vue'
import Select from '@/components/common/Select.vue'
@ -167,13 +196,14 @@ import ExportButton from '@/components/common/ExportButton.vue'
import type { Column } from '@/components/common/types'
import { designAPI, workAPI } from '@/api'
import { useOAList } from '@/composables/useOAList'
import { formatDateTimeToMinute } from '@/utils/format'
import { formatDateTimeToMinute, formatRelativeTime } from '@/utils/format'
import { badgeClass, formatSeconds, runAction, workStatusLabel, workStatusVariant } from '@/utils/oa'
import { startFormLocation } from '@/utils/startPage'
import type { WorkItem } from '@/types'
const { t } = useI18n()
const router = useRouter()
const { phoneShell } = useMobileShell()
const { items, loading, params, pagination, reload, debouncedReload, handlePageChange, handlePageSizeChange } =
useOAList(
@ -205,7 +235,10 @@ const exportQuery = computed(() => ({ scope: 'created', ...params }))
const processOptions = computed(() => [
{ value: '', label: t('common.all') },
...processes.value.map((process) => ({ value: process.id, label: process.name }))
...processes.value.map((process) => ({
value: process.id,
label: process.name
}))
])
const statusOptions = computed(() => [
@ -215,6 +248,38 @@ const statusOptions = computed(() => [
{ value: 'terminated', label: t('work.statusTerminated') }
])
/* ------------------------------------------------------------------ 手机版式
* 我发起的卡片:叫什么、哪个流程、什么状态、现在压在谁那一环。被挂起的单子左边给一道
* 黄条——那不是你批得慢,是管理员按住了,扫一眼就该知道不必再等。
* ----------------------------------------------------------------------- */
const cards = computed<MobileCardRow[]>(() =>
feed.value.map((row) => ({
key: String(row.id),
title: row.title,
meta: [row.process_name, row.serial, formatRelativeTime(row.start_time)].filter(Boolean),
badges: [
{
text: workStatusLabel(row.status),
cls: `badge-${workStatusVariant(row.status)}`
},
...(row.current_activity_names ? [{ text: row.current_activity_names, cls: 'badge-primary' }] : []),
...(row.paused ? [{ text: t('task.suspended'), cls: 'badge-gray' }] : [])
],
tail: t('mobile.viewProgress'),
level: (row.paused ? 'warn' : '') as MobileCardRow['level']
}))
)
const { feed, finished, loadMore } = useMobileFeed({
items,
loading,
pagination,
handlePageChange,
keyOf: (row: WorkItem) => row.id
})
function openById(id: string) {
const row = feed.value.find((item) => String(item.id) === id)
if (row) openWork(row)
}
function openWork(row: WorkItem) {
router.push({ name: 'work-detail', params: { job: row.job } })
}
@ -242,7 +307,9 @@ async function confirmDelete() {
const row = pendingDelete.value
pendingDelete.value = null
if (!row) return
const done = await runAction(() => workAPI.deleteJob(row.job), { success: t('common.deleteSuccess') })
const done = await runAction(() => workAPI.deleteJob(row.job), {
success: t('common.deleteSuccess')
})
if (done !== null) reload()
}

View File

@ -1,10 +1,28 @@
<template>
<TablePageLayout>
<!-- 已办在手机上也是一串卡片:数据、筛选、分页都还是 useOAList 那一份,只是不摆表格。 -->
<MobileCardList
v-if="phoneShell"
v-model:keyword="params.keyword"
:title="t('nav.myDone')"
:rows="cards"
:loading="loading"
:finished="finished"
:total="pagination.total"
:show-expired="false"
:empty-hint="t('common.noData')"
@update:keyword="debouncedReload"
@refresh="reload"
@load-more="loadMore"
@open="openById"
/>
<TablePageLayout v-else>
<template #actions>
<div class="page-header mb-0 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 class="page-title">{{ t('nav.myDone') }}</h2>
<p class="page-description">{{ t('common.total', { count: pagination.total }) }}</p>
<p class="page-description">
{{ t('common.total', { count: pagination.total }) }}
</p>
</div>
<div class="flex items-center gap-2">
<ExportButton kind="tasks" :query="exportQuery" :name="t('nav.myDone')" />
@ -56,9 +74,13 @@
<!-- 标题与副标题各占一行、超出打点:表格是固定布局,这一列拿的是剩余空间,
所以封顶交给格子本身(max-w-full),不用再把像素数写死在内容上。悬浮给全名。 -->
<div class="max-w-full">
<p class="truncate font-medium text-gray-900 dark:text-dark-100" :title="row.title">{{ row.title }}</p>
<p class="truncate font-medium text-gray-900 dark:text-dark-100" :title="row.title">
{{ row.title }}
</p>
<p class="mt-0.5 flex items-center gap-1.5 text-xs text-gray-400">
<span class="min-w-0 truncate" :title="`${row.serial} · ${row.process_name}`">{{ row.serial }} · {{ row.process_name }}</span>
<span class="min-w-0 truncate" :title="`${row.serial} · ${row.process_name}`"
>{{ row.serial }} · {{ row.process_name }}</span
>
<span
v-if="handledTimes(row) > 1"
class="badge badge-gray"
@ -70,11 +92,21 @@
</div>
</template>
<template #cell-activity_name="{ row }">
<span class="badge max-w-full truncate badge-primary" :title="row.activity_name">{{ row.activity_name }}</span>
<p class="mt-1 text-xs text-gray-400">{{ processingTypeLabel(row.processing_type) }}</p>
<span class="badge max-w-full truncate badge-primary" :title="row.activity_name">{{
row.activity_name
}}</span>
<p class="mt-1 text-xs text-gray-400">
{{ processingTypeLabel(row.processing_type) }}
</p>
</template>
<template #cell-route_name="{ row }">
<span v-if="row.route_name" class="badge max-w-full truncate" :class="resultBadgeClass(row)" :title="row.route_name">{{ row.route_name }}</span>
<span
v-if="row.route_name"
class="badge max-w-full truncate"
:class="resultBadgeClass(row)"
:title="row.route_name"
>{{ row.route_name }}</span
>
<span v-else class="text-xs text-gray-400">--</span>
</template>
<template #cell-opinion="{ row }">
@ -114,7 +146,11 @@
<!-- 撤不回来的这一条得说原因:归档的单子不给按钮是对的,但什么都不说,
人只会一遍遍去点别的按钮。可那句话说得长,摊在这一列里会把整列撑开,
前面几列的流程信息反而一格都看不见,所以收成一枚图标,原因交给悬浮提示。 -->
<HelpTooltip v-else-if="showBlocker(row)" :content="t('task.cannotReset') + ':' + row.recall_blocker" width-class="w-96">
<HelpTooltip
v-else-if="showBlocker(row)"
:content="t('task.cannotReset') + ':' + row.recall_blocker"
width-class="w-96"
>
<template #trigger>
<span
data-test="recall-blocked"
@ -160,6 +196,10 @@ import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import TablePageLayout from '@/components/layout/TablePageLayout.vue'
import MobileCardList from '@/components/oa/mobile/MobileCardList.vue'
import type { MobileCardRow } from '@/components/oa/mobile/MobileCardList.vue'
import { useMobileFeed } from '@/composables/useMobileFeed'
import { useMobileShell } from '@/composables/useMobileShell'
import DataTable from '@/components/common/DataTable.vue'
import Pagination from '@/components/common/Pagination.vue'
import Select from '@/components/common/Select.vue'
@ -173,13 +213,14 @@ import HelpTooltip from '@/components/common/HelpTooltip.vue'
import type { Column } from '@/components/common/types'
import { designAPI, taskAPI } from '@/api'
import { useOAList } from '@/composables/useOAList'
import { formatDateTimeToMinute } from '@/utils/format'
import { formatDateTimeToMinute, formatRelativeTime } from '@/utils/format'
import { formatSeconds, processingTypeLabel, runAction } from '@/utils/oa'
import { resultBadgeClass } from '@/utils/approvalRecord'
import type { TaskCompletedItem } from '@/types'
const { t } = useI18n()
const router = useRouter()
const { phoneShell } = useMobileShell()
const { items, loading, params, pagination, reload, debouncedReload, handlePageChange, handlePageSizeChange } =
useOAList(
@ -200,20 +241,75 @@ const columns = computed<Column[]>(() => [
// 环节、结果、处理时间各分走三四千)。固定布局下这些列宽是实打实的像素,
// 长环节名自己在格子里打点,不再回头挤压别人。
{ key: 'title', label: t('common.title') },
{ key: 'activity_name', label: t('task.activity'), class: 'w-[116px] overflow-hidden' },
{ key: 'route_name', label: t('task.route'), class: 'w-[92px] overflow-hidden' },
{
key: 'activity_name',
label: t('task.activity'),
class: 'w-[116px] overflow-hidden'
},
{
key: 'route_name',
label: t('task.route'),
class: 'w-[92px] overflow-hidden'
},
{ key: 'opinion', label: t('task.opinion') },
{ key: 'completed_time', label: t('task.startedAt'), class: 'w-[152px] overflow-hidden' },
{ key: 'actions', label: t('common.actions'), class: 'w-[116px] overflow-hidden' }
{
key: 'completed_time',
label: t('task.startedAt'),
class: 'w-[152px] overflow-hidden'
},
{
key: 'actions',
label: t('common.actions'),
class: 'w-[116px] overflow-hidden'
}
])
const exportQuery = computed(() => ({ scope: 'completed', ...params }))
const processOptions = computed(() => [
{ value: '', label: t('common.all') },
...processes.value.map((process) => ({ value: process.id, label: process.name }))
...processes.value.map((process) => ({
value: process.id,
label: process.name
}))
])
/* ------------------------------------------------------------------ 手机版式
* 已办卡片说三件事:这张单叫什么、我在哪一环表了什么态、什么时候办的。
* 桌面上那一整列审批意见手机上不摆——自己批过什么心里有数,要看原文点进单据。
* ----------------------------------------------------------------------- */
const cards = computed<MobileCardRow[]>(() =>
feed.value.map((row) => ({
key: String(row.id),
title: row.title,
meta: [row.process_name, formatRelativeTime(row.completed_time)].filter(Boolean),
badges: [
{ text: row.activity_name, cls: 'badge-primary' },
...(row.route_name ? [{ text: row.route_name, cls: resultBadgeClass(row) }] : []),
...(handledTimes(row) > 1
? [
{
text: t('mobile.handledTimes', { count: handledTimes(row) }),
cls: 'badge-gray'
}
]
: [])
],
tail: t('mobile.viewWork'),
level: '' as MobileCardRow['level']
}))
)
const { feed, finished, loadMore } = useMobileFeed({
items,
loading,
pagination,
handlePageChange,
keyOf: (row: TaskCompletedItem) => row.id
})
function openById(id: string) {
const row = feed.value.find((item) => String(item.id) === id)
if (row) openWork(row)
}
function openWork(row: TaskCompletedItem) {
router.push({ name: 'work-detail', params: { job: row.job } })
}
@ -235,7 +331,9 @@ function recall(row: TaskCompletedItem) {
async function confirmRecall() {
const row = pending.value
if (!row) return
const done = await runAction(() => taskAPI.resetCompleted(row.id), { success: t('common.operationSuccess') })
const done = await runAction(() => taskAPI.resetCompleted(row.id), {
success: t('common.operationSuccess')
})
confirmShow.value = false
if (done !== null) reload()
}

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