fix(workflow): wire create.ts caller, real webapi, try/catch, lint routing all forms, CLAUDE.md compliance

This commit is contained in:
ssw committed 2026-07-28 18:23:49 +08:00
1 parent 22d8111462
commit e03418d3ee
6 files changed
+304 -112

No files matched your search

+71 -33
View File
@@ -1,36 +1,53 @@
/**
* workflow 审批人变量解析 (webapi hardening)
* workflow 审批人变量解析.
*
* 镜像 web 端 FlowApproverSelect + ssw-common build-workflow 的 candidateResolver.
*
* 设计原则:
* - 解析 BPMN userTask assignee 表达式, 返回候选人列表 + 失败原因 (reason).
* - 失败原因显式化, 方便 _semantic_lint.ts 阻断坏 BPMN 进后端 Flowable 部署.
* - 不直接调 JnpfClient, 接受 webapi 容器 (resolveApproverExpr 是纯函数, 易于测试 + 复用).
* 解析 BPMN userTask assignee 表达式, 返回候选人列表 + 失败原因 (reason).
* 与 _semantic_lint 协同: 阻断坏 BPMN 进后端 Flowable 部署.
*
* 支持的表达式:
* - `role:<enCode>` → 调用 webapi.getUserListByRole(enCode)
* - `${deptManager}` → 调用 webapi.getDeptManager() (web 端发起人部门主管)
* - `${currentUser}` → 调用 webapi.getCurrentUser() (运行时上下文)
* - 显式 id (u\d+|v\d+) → 视为单候选人占位 (不解析, 视为合法)
* - `role:<enCode>` → webapi.getUserListByRole(enCode)
* - `${deptManager}` → webapi.getDeptManager() (发起人部门主管)
* - `${currentUser}` → webapi.getCurrentUser() (当前登录用户)
* - 显式 id (6+ 位数字) → 视为单候选人占位
*
* 保留关键字 (reserved keyword, 不允许作为审批人):
* - `initiator` / `any` / `starter` / `currentUser` 直接使用 (≠ ${currentUser} 表达式)
* 这些关键字在 BPMN flowable 引擎层有特殊语义, dacli 不应混淆 (避免双重解析).
* - `initiator` / `any` / `starter` / `currentUser` 字面量
* 估算匹配: 这些关键字在 Flowable 引擎层有特殊语义, dacli 不应混淆 (避免双重解析).
*
* 错误时返回空 candidates + reason 字符串, 调用方按需阻断.
* 异步 I/O 包装: 所有 webapi 调用都包在 try/catch, 避免 lint 流程被异常打断.
*/
/** 解析候选人所需的最小 webapi 契约. 真实方法在生产调用点 (create.ts) 注入. */
export interface ResolveWebapi {
/** 角色 enCode → 用户列表. 真实 API 待 wiring (web 端 permission/user.ts 无 byRole 入口). */
getUserListByRole?: (enCode: string) => Promise<Array<{ id: string; name: string }>>
/** 发起人部门主管. 真实 API 待 wiring (web 端 permission/organize.ts 无 manager 入口). */
getDeptManager?: () => Promise<Array<{ id: string; name: string }>>
/** 当前登录用户. 对应 JNPF /api/oauth/CurrentUser (src/webapi/user.ts getUserInfoApi). */
getCurrentUser?: () => Promise<{
id?: string
userId?: string
realName?: string
userName?: string
account?: string
userAccount?: string
} | null | undefined>
}
export interface ResolveCtx {
/** webapi 容器 (测试时可注入 mock). */
webapi: any
webapi?: ResolveWebapi
}
export interface ResolveResult {
candidates: Array<{ id: string; name: string }>
reason?: 'no users in dept' | 'no such role' | 'unknown expression' | 'reserved keyword' | 'api error'
reason?: 'no users in dept' | 'no current user' | 'no such role' | 'unknown expression' | 'reserved keyword' | 'api error'
}
/** 不允许直接当作 assignee 表达式使用的关键字. */
const RESERVED = new Set(['initiator', 'any', 'starter', 'currentUser'])
/** 不允许直接当作 assignee 表达式使用的关键字 (统一小写匹配).
* 注: ${currentUser} 这种变量包装形式是合法的 getter 调用, 不在此列. */
const RESERVED = new Set(['initiator', 'any', 'starter'])
/**
* 解析 BPMN userTask assignee 表达式.
@@ -45,42 +62,63 @@ export async function resolveApproverExpr(expr: string, ctx: ResolveCtx): Promis
return { candidates: [], reason: 'unknown expression' }
}
// 保留关键字 (initiator / any / starter / currentUser 字面量)
if (RESERVED.has(e)) {
// 1. 保留关键字 (unwrap ${...} 后, 不区分大小写检查)
const innerNoVar = e.replace(/^\$\{(.+)\}$/, '$1').trim().toLowerCase()
if (RESERVED.has(innerNoVar)) {
return { candidates: [], reason: 'reserved keyword' }
}
// role:xxx — 角色 enCode
const roleMatch = /^role:(.+)$/.exec(e)
// 2. role:xxx — 角色 enCode (trim 内部空白)
const roleMatch = /^role:\s*(.+?)\s*$/.exec(e)
if (roleMatch) {
const list = (await ctx.webapi?.getUserListByRole?.(roleMatch[1])) ?? []
const enCode = roleMatch[1]
const list = await safeCall(() => ctx.webapi?.getUserListByRole?.(enCode))
if (!Array.isArray(list)) return { candidates: [], reason: 'api error' }
return list.length ? { candidates: list } : { candidates: [], reason: 'no such role' }
}
// ${var} — 运行时变量
// 3. ${var} — 运行时变量
const varMatch = /^\$\{(.+)\}$/.exec(e)
if (varMatch) {
const name = varMatch[1].trim()
if (name === 'deptManager') {
const list = (await ctx.webapi?.getDeptManager?.()) ?? []
const list = await safeCall(() => ctx.webapi?.getDeptManager?.())
if (!Array.isArray(list)) return { candidates: [], reason: 'api error' }
return list.length ? { candidates: list } : { candidates: [], reason: 'no users in dept' }
}
if (name === 'currentUser') {
const me = await ctx.webapi?.getCurrentUser?.()
if (me && (me.id || me.userId)) {
const id = String(me.id ?? me.userId)
const name2 = String(me.realName ?? me.userName ?? me.account ?? id)
return { candidates: [{ id, name: name2 }] }
}
return { candidates: [], reason: 'no users in dept' }
const me = await safeCall(() => ctx.webapi?.getCurrentUser?.())
if (me === undefined) return { candidates: [], reason: 'api error' }
if (!me) return { candidates: [], reason: 'no current user' }
// JNPF 用空字符串表 unset (而不是 null), 用 || 链而非 ??
const id = String(me.userId || me.id || '')
const displayName = String(me.realName || me.userName || me.userAccount || me.account || id)
if (!id) return { candidates: [], reason: 'no current user' }
return { candidates: [{ id, name: displayName }] }
}
return { candidates: [], reason: 'unknown expression' }
}
// 显式 id (u\d+ 或 v\d+, JNPF userId / Vben v-id 风格) — 视为单候选人占位
if (/^[uv]\d+$/.test(e)) {
// 4. 显式 id (JNPF userId 风格, 6+ 位数字) — 视为单候选人占位
if (/^\d{6,}$/.test(e)) {
return { candidates: [{ id: e, name: e }] }
}
return { candidates: [], reason: 'unknown expression' }
}
/**
* 安全调用 webapi 方法.
* - 正常返回: webapi 返回值 (任意类型, 包括 null — 调用方区分 list / object)
* - 抛错: 返回 undefined (调用方按 'api error' 处理)
*/
async function safeCall<T>(fn: () => Promise<T> | undefined): Promise<T | undefined> {
try {
return await fn()
} catch {
return undefined
}
}
+14 -25
View File
@@ -1,5 +1,5 @@
/**
* workflow 语义 lint (webapi hardening)
* workflow 语义 lint.
*
* 与 BPMN layout lint 分离: layout 自动修复不掩盖语义错误.
* 使用 bpmn-moddle 解析 (项目已有依赖 ^10.0.0).
@@ -9,7 +9,7 @@
* - semanticLint 基于原始 BPMN XML 解析 (bpmn-moddle), 检查:
* 1. 节点完整性 (no start / no end)
* 2. 多结束节点无合流网关
* 3. userTask assignee 解析 (空字符串 / ${var} 无法解析)
* 3. userTask assignee 解析 (空 / ${var} / role / 关键字 / 显式 id)
*
* 设计原则: 在 Save(type=1) 之前阻断, 不让坏 BPMN 进入后端 Flowable 部署阶段.
*
@@ -21,7 +21,7 @@
*/
import { BpmnModdle } from 'bpmn-moddle'
import { resolveApproverExpr } from './_approver_resolve.ts'
import { resolveApproverExpr, type ResolveWebapi } from './_approver_resolve.ts'
export interface SemanticDiagnostic {
nodeId: string
@@ -35,17 +35,15 @@ export interface SemanticResult {
}
export interface ResolverCtx {
/** webapi 容器 (T5 接入). 优先使用, 解析失败时返回 reason. */
webapi?: any
/** 旧版 fallback (T4 阶段使用). 仅 webapi 缺失时启用, 兼容老调用点. */
candidateResolver?: (assigneeExpr: string) => Array<{ id: string; name: string }>
/** 候选人解析所需的最小 webapi 契约. 任意方法缺失时按 'api error' 阻断. */
webapi?: ResolveWebapi
}
/**
* 跑 workflow 语义 lint.
*
* @param xml - 原始 BPMN 2.0 XML
* @param ctx - 解析上下文 (T4 阶段 candidateResolver 占位, T5 接 resolveApproverExpr)
* @param xml 原始 BPMN 2.0 XML
* @param ctx 解析上下文 (webapi 容器, 供 resolveApproverExpr 使用)
*/
export async function semanticLint(xml: string, ctx: ResolverCtx): Promise<SemanticResult> {
const errors: string[] = []
@@ -115,22 +113,13 @@ export async function semanticLint(xml: string, ctx: ResolverCtx): Promise<Seman
continue
}
// 3b. assignee 是 ${var} 表达式, 尝试解析
if (assignee && /\$\{.+\}/.test(assignee)) {
let resolved: Array<{ id: string; name: string }> = []
let reason: string | undefined
if (ctx.webapi) {
const r = await resolveApproverExpr(assignee, { webapi: ctx.webapi })
resolved = r.candidates
reason = r.reason
} else if (ctx.candidateResolver) {
// 向后兼容: T4 阶段调用点只传 candidateResolver
resolved = ctx.candidateResolver(assignee) || []
if (resolved.length === 0) reason = 'no candidate'
}
if (resolved.length === 0) {
errors.push(`userTask ${ut.id}: assignee ${assignee} unresolved (${reason ?? 'no candidate'})`)
diagnostics.push({ nodeId: ut.id, message: `unresolved: ${assignee}${reason ? ` (${reason})` : ''}` })
// 3b. 路由 ALL forms 到 resolveApproverExpr (含 reserved keyword / role / ${var} / 显式 id / 空字符串)
if (assignee) {
const r = await resolveApproverExpr(assignee, { webapi: ctx.webapi })
if (r.candidates.length === 0) {
const reason = r.reason ?? 'unknown expression'
errors.push(`userTask ${ut.id}: assignee ${assignee} unresolved (${reason})`)
diagnostics.push({ nodeId: ut.id, message: `unresolved: ${assignee} (${reason})` })
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ export interface StepValidation {
}
/** 语义 lint — workflow/create.ts 在 Save(type=1) 之前调用, 阻断坏 BPMN 进后端.
* T4: 多结束无合并 / 无 start / assignee 空 / ${var} 无法解析 4 场景. */
* 覆盖: 多结束无合并 / 无 start / assignee 空 / ${var} 解析失败 / 保留关键字 / 显式 id 失败. */
export { semanticLint } from './_semantic_lint.ts'
export type { SemanticResult, SemanticDiagnostic, ResolverCtx } from './_semantic_lint.ts'
+14 -3
View File
@@ -28,6 +28,7 @@ import { callAiWorkflow, detectTrivialFlowXml } from '../form/_ai.ts'
import { buildFlowNodes, validateFlowNodeStructure } from './_webapi_helpers.ts'
import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts'
import { initWebapi, loadWorkflow } from '../../webapi/workflow.ts'
import { getUserInfoApi } from '../../webapi/user.ts'
import { validateWorkflowCreate, semanticLint } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): enCode/fullName strip 已统一到 runCommandAutoFix (commands/_auto_fix.ts), 不再 inline 调 autoStripEnCode/autoStripFullName (替代原 line 96-112 的 inline 调用 + warn log, BS-新38/BS-新52).
@@ -380,12 +381,22 @@ export function buildWorkflowCreateCommand(): Command {
log.ok(` ↳ ${structCheck.okMessage}`)
}
// 语义 lint (T4) — 阻断坏 BPMN 进后端 Flowable 部署.
// 语义 lint — 阻断坏 BPMN 进后端 Flowable 部署.
// 与 _webapi_helpers.validateFlowNodeStructure 互补:
// - validateFlowNodeStructure 检查 flowNodes Map 形态 (数量/类型)
// - semanticLint 检查原始 flowXml BPMN 语义 (assignee 解析, 多结束无合并)
// T4 阶段 candidateResolver 是占位, T5 会替换为真实 resolveApproverExpr.
const semantic = await semanticLint(flowXml, { candidateResolver: () => [] })
// 注入真实 webapi: getCurrentUser 调 JNPF /api/oauth/CurrentUser (src/webapi/user.ts getUserInfoApi).
// getUserListByRole / getDeptManager 暂未在 web 端暴露, 保留 undefined → 解析时会 'api error' 阻断.
const webapi = {
getCurrentUser: async () => {
try {
return await getUserInfoApi(c, { systemCode: c.appCode, isBackend: 1 })
} catch {
return null
}
},
}
const semantic = await semanticLint(flowXml, { webapi })
if (!semantic.ok) {
log.error(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误):`)
for (const e of semantic.errors) {