unis-oa/frontend/src/utils/formLayout.ts

662 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* The form layout engine shared by the sheet designer and the runtime renderer.
*
* A form is a spreadsheet: 12 columns, unlimited rows, and every field is a
* merged cell that starts at (row, col) and covers `units` columns. Older forms
* only stored `span: 12 | 24` plus `layout.columns: 1 | 2`; `toSheet` folds
* those into the same 12-column grid so both renderers agree.
*/
import type { FieldType, FormFieldDef, FormSchema } from '@/types'
import { autoRuleProblems } from '@/utils/autoRule'
import { autoPresetProblems } from '@/utils/autoPreset'
import {
FILE_LIMIT_TYPES,
SPACER_MAX_HEIGHT,
SPACER_MIN_HEIGHT,
TEXT_LIMIT_TYPES,
embedConfigProblems,
fileConfigProblems,
monthsConfigProblems,
textConfigProblems,
unitProblem,
validateTableField
} from '@/utils/formRuntime'
import { fieldTitleRuleProblem } from '@/utils/titleRule'
import { tabKeyOf, tabProblems, tabsOf } from '@/utils/tabPages'
export const GRID_COLS = 12
/** Field types that need an option list. */
export const OPTION_FIELD_TYPES = ['select', 'radio', 'checkbox']
/**
* 这几类字段用原生 input 就够了,值仍是字符串。
* 主表和明细表的格子共用,所以放在这里而不是某个组件里。
*/
export const HTML_INPUT_TYPES: Partial<Record<FieldType, string>> = {
mobile: 'tel',
email: 'email',
url: 'url',
idcard: 'text',
time: 'time',
month: 'month',
address: 'text'
}
export function htmlInputType(type: FieldType): string {
return HTML_INPUT_TYPES[type] ?? ''
}
/** 只有展示作用、没有录入控件的类型。 */
export const NON_INPUT_TYPES = ['divider', 'description', 'group', 'spacer', 'embed', 'tabs']
/**
* 没有录入控件、也不该参与「必填」校验的类型:分割线、说明文字、隐藏字段,
* 以及由系统带出的字段(值由后端在发起时写入,不该卡住提交)。
*/
export const NON_FILLABLE_TYPES = ['divider', 'description', 'group', 'spacer', 'hidden', 'auto', 'formula', 'embed', 'tabs']
export function isFillable(field: { type: string }): boolean {
return !NON_FILLABLE_TYPES.includes(field.type)
}
/**
* 不需要字段标题的类型:只有空白格。它的 label 上屏后一个字都不显示,
* 逼设计者编一句标题等于让人写废话;分组标题的 label 就是那行抬头,缺了这段
* 就没有名字,所以照旧要。后端 api/design.py:LABELLESS_TYPES 是同一份口径。
*/
export const LABELLESS_TYPES = ['spacer']
/** 流程标题字段(``type=title``);一张表单只认第一个,与后端 titles.form_title_field 同口径。 */
export function titleFieldOf(fields?: FormFieldDef[] | null): FormFieldDef | null {
return (fields ?? []).find((field) => field?.type === 'title' && Boolean((field.key ?? '').trim())) ?? null
}
/**
* 系统自动带出的取值来源,key 必须和后端 ``service/autofill.py`` 对齐:
* 后端在发起时把 PERSISTED 那些写进 work.data,RUNTIME 那两个由前端按当前环节现算。
*/
export const AUTO_VALUE_KEYS = [
'creator',
'creatorAccount',
'creatorUnit',
'creatorUnitPath',
'creatorUnitManager',
'creatorLeader',
'processName',
'serial',
'now',
'today',
'activityName',
'handler'
] as const
/** 前端自己能算出来的系统值(不用等后端回填就能在发起页显示)。 */
export const LOCAL_AUTO_KEYS = [
'creator',
'creatorAccount',
'creatorUnit',
'creatorUnitPath',
'processName',
'now',
'today',
'activityName',
'handler'
] as const
export function isAutoLocal(key: string): boolean {
return (LOCAL_AUTO_KEYS as readonly string[]).includes(key)
}
export const FIELD_TYPES: FieldType[] = [
'text',
'title',
'textarea',
'richtext',
'number',
'money',
'date',
'datetime',
'time',
'daterange',
'month',
'months',
'year',
'timerange',
'mobile',
'email',
'idcard',
'url',
'address',
'location',
'select',
'picker',
'radio',
'checkbox',
'switch',
'rate',
'dept',
'cascader',
'week',
'user',
'attachment',
'image',
'signature',
'relation',
'auto',
'table',
'formula',
'group',
'divider',
'description',
'spacer',
'hidden',
// 外部页面:把别的业务系统的页面嵌进这一格(docs/embed-page-field-design.md)
'embed',
// 标签页:把这张单切成几页,其中一页可以整页让给外部系统(docs/form-tabs-embed-design.md)
'tabs'
]
export interface SheetCell {
key: string
/** Position inside the persisted `fields` array. */
index: number
field: FormFieldDef
/** 1-based row, like a spreadsheet row number. */
row: number
/** 1-based first column, 1..GRID_COLS. */
col: number
/** Merged columns, 1..GRID_COLS. */
units: number
/** Nothing else shares this row. */
alone: boolean
}
export interface Sheet {
cols: number
rows: number
cells: SheetCell[]
}
export function hasOptions(type: string): boolean {
return OPTION_FIELD_TYPES.includes(type)
}
/** True when the schema already stores explicit 12-column placements. */
export function isGridLayout(schema?: FormSchema | null): boolean {
const layout = schema?.layout as ({ grid?: number; columns?: number } | undefined) ?? undefined
return layout?.grid === GRID_COLS || layout?.columns === GRID_COLS
}
/** Legacy `columns` value, kept for the single-column switch old forms used. */
export function columnsOf(schema?: FormSchema | null): number {
const columns = schema?.layout?.columns ?? 2
return columns <= 1 ? 1 : 2
}
export function clampUnits(units: number | undefined, fallback = 6): number {
const value = Math.round(Number(units ?? fallback))
if (!Number.isFinite(value)) return fallback
return Math.min(GRID_COLS, Math.max(1, value))
}
/** How many of the old 1/2 columns a field used. */
function legacyCells(field: FormFieldDef, columns: number): number {
if (columns <= 1) return 1
if (field.type === 'divider') return columns
return (field.span ?? 12) >= 24 ? columns : 1
}
/** Old span (12 = half row, 24 = full row) converted into 12-column units. */
export function unitsForLegacy(field: FormFieldDef, columns: number): number {
const width = columns <= 1 ? 1 : columns
return legacyCells(field, width) * (GRID_COLS / width)
}
/**
* Reading-order placement, the same walk CSS auto-flow performs: a field that
* does not fit in what is left of the row starts the next row and the leftover
* cells stay empty.
*/
export function flowCells(fields: FormFieldDef[], columns = GRID_COLS): SheetCell[] {
const cells: SheetCell[] = []
let row = 1
let col = 1
fields.forEach((field, index) => {
const units = clampUnits(field.span, columns <= 1 ? GRID_COLS : 6)
if (col + units - 1 > columns) {
row += 1
col = 1
}
cells.push({ key: field.key, index, field, row, col, units, alone: false })
col += units
if (col > columns) {
row += 1
col = 1
}
})
return decorate(cells)
}
function decorate(cells: SheetCell[], columns = GRID_COLS): SheetCell[] {
const perRow = new Map<number, number>()
cells.forEach((cell) => perRow.set(cell.row, (perRow.get(cell.row) ?? 0) + 1))
return cells
.map((cell) => ({
...cell,
alone: (perRow.get(cell.row) ?? 0) === 1,
units: Math.min(cell.units, columns - cell.col + 1)
}))
.sort((a, b) => a.row - b.row || a.col - b.col)
.map((cell, index) => ({ ...cell, index }))
}
/**
* Resolve overlaps by sliding the later cell to the right, wrapping to the next
* row when it runs out of columns. Inserting into an occupied cell therefore
* behaves like Excel's insert: the existing content moves along.
*/
export function normalize(cells: SheetCell[], columns = GRID_COLS): SheetCell[] {
const ordered = [...cells].sort((a, b) => a.row - b.row || a.col - b.col)
const occupied = new Set<string>()
const placed: SheetCell[] = []
ordered.forEach((input) => {
const cell = { ...input }
cell.units = clampUnits(cell.units, 6)
cell.row = Math.max(1, Math.round(cell.row) || 1)
cell.col = Math.min(Math.max(1, Math.round(cell.col) || 1), columns)
let guard = columns * (ordered.length + 2) * 2
while (guard > 0) {
guard -= 1
if (cell.col + cell.units - 1 > columns) {
cell.col = 1
cell.row += 1
continue
}
let clash = false
for (let offset = 0; offset < cell.units; offset += 1) {
if (occupied.has(`${cell.row}:${cell.col + offset}`)) clash = true
}
if (!clash) break
cell.col += 1
}
for (let offset = 0; offset < cell.units; offset += 1) {
occupied.add(`${cell.row}:${cell.col + offset}`)
}
placed.push(cell)
})
return decorate(placed, columns)
}
/** Build the sheet for any schema, migrating legacy span/column layouts. */
export function toSheet(schema?: FormSchema | null): Sheet {
const fields = schema?.fields ?? []
const cols = GRID_COLS
if (!isGridLayout(schema)) {
// Fold the old 1/2 column flow into the same grid: each legacy cell becomes
// `cols / legacyColumns` merged columns, and a wrap still leaves a hole.
const legacyColumns = columnsOf(schema)
const scale = cols / legacyColumns
const cells: SheetCell[] = []
let row = 1
let slot = 1
fields.forEach((field, index) => {
const used = Math.min(legacyCells(field, legacyColumns), legacyColumns)
if (slot - 1 + used > legacyColumns) {
row += 1
slot = 1
}
cells.push({ key: field.key, index, field, row, col: (slot - 1) * scale + 1, units: used * scale, alone: false })
slot += used
if (slot > legacyColumns) {
row += 1
slot = 1
}
})
return finalize(cells, cols)
}
const cells: SheetCell[] = []
const homeless: FormFieldDef[] = []
const homelessIndex: number[] = []
fields.forEach((field, index) => {
const row = Number(field.row ?? 0)
const col = Number(field.col ?? 0)
const units = clampUnits(field.span, field.type === 'divider' ? cols : 6)
if (row >= 1 && col >= 1) {
cells.push({ key: field.key, index, field, row, col, units, alone: false })
return
}
homeless.push(field)
homelessIndex.push(index)
})
// Fields without a stored position (hand-written JSON, imported forms) flow in
// below the placed ones instead of piling onto row one.
if (homeless.length) {
const baseRow = cells.reduce((max, item) => Math.max(max, item.row), 0)
flowCells(homeless, cols).forEach((cell, position) => {
const field = homeless[position]
cells.push({
key: field.key,
index: homelessIndex[position],
field,
row: cell.row + baseRow,
col: cell.col,
units: cell.units,
alone: false
})
})
}
return finalize(cells, cols)
}
function finalize(cells: SheetCell[], cols: number): Sheet {
const placed = normalize(cells, cols)
return { cols, rows: placed.reduce((max, cell) => Math.max(max, cell.row), 0), cells: placed }
}
/** Turn the sheet back into the persisted schema; `extras` keeps unknown keys. */
export function fromSheet(sheet: Sheet, extras: Record<string, unknown> = {}): FormSchema {
return {
fields: sheet.cells.map((cell) => ({ ...cell.field, row: cell.row, col: cell.col, span: cell.units })),
layout: { ...extras, columns: GRID_COLS, grid: GRID_COLS }
} as FormSchema
}
export function cellAt(sheet: Sheet, row: number, col: number): SheetCell | undefined {
return sheet.cells.find((cell) => cell.row === row && col >= cell.col && col < cell.col + cell.units)
}
export function rowsOf(sheet: Sheet): number {
return sheet.rows
}
/** Every column the given rows occupy, useful for row-header highlighting. */
export function keysInRows(sheet: Sheet, rows: number[]): string[] {
return sheet.cells.filter((cell) => rows.includes(cell.row)).map((cell) => cell.key)
}
export function moveCellsBy(cells: SheetCell[], keys: string[], dRow: number, dCol: number, columns = GRID_COLS): SheetCell[] {
const targets = new Set(keys)
const moved = cells.map((cell) =>
targets.has(cell.key)
? { ...cell, row: Math.max(1, cell.row + dRow), col: Math.max(1, cell.col + dCol) }
: { ...cell }
)
// The dragged fields claim the target cell and the rest of the row moves out
// of the way, which is what a drop should feel like.
const ordered = [...moved].sort((a, b) => Number(targets.has(b.key)) - Number(targets.has(a.key)))
return normalize(ordered, columns)
}
export function placeCell(cells: SheetCell[], keys: string[], row: number, col: number, columns = GRID_COLS): SheetCell[] {
const targets = cells.filter((cell) => keys.includes(cell.key)).sort((a, b) => a.row - b.row || a.col - b.col)
if (!targets.length) return cells
const anchor = targets[0]
return moveCellsBy(cells, keys, row - anchor.row, col - anchor.col, columns)
}
/**
* Grow or shrink a field. It stops at whatever is already on its right, so
* dragging the handle wider can never swallow the neighbouring cell.
*/
export function resizeCell(cells: SheetCell[], key: string, units: number, columns = GRID_COLS): SheetCell[] {
const target = cells.find((cell) => cell.key === key)
if (!target) return cells
const right = cells.filter((cell) => cell.key !== key && cell.row === target.row && cell.col > target.col).map((cell) => cell.col)
const limit = right.length ? Math.min(...right) - target.col : columns - target.col + 1
const width = Math.max(1, Math.min(units, limit))
return normalize(
cells.map((cell) => (cell.key === key ? { ...cell, units: width } : { ...cell })),
columns
)
}
export function spanCells(cells: SheetCell[], keys: string[], units: number, columns = GRID_COLS): SheetCell[] {
const targets = new Set(keys)
return normalize(
cells.map((cell) => (targets.has(cell.key) ? { ...cell, units: Math.max(1, Math.min(units, columns)) } : { ...cell })),
columns
)
}
export function alignLeft(cells: SheetCell[], keys: string[], columns = GRID_COLS): SheetCell[] {
const targets = new Set(keys)
return normalize(
cells.map((cell) => (targets.has(cell.key) ? { ...cell, col: 1 } : { ...cell })),
columns
)
}
export function insertRow(cells: SheetCell[], row: number, columns = GRID_COLS): SheetCell[] {
return normalize(
cells.map((cell) => (cell.row >= row ? { ...cell, row: cell.row + 1 } : { ...cell })),
columns
)
}
export function deleteRow(cells: SheetCell[], row: number, columns = GRID_COLS): SheetCell[] {
const kept = cells
.filter((cell) => cell.row !== row)
.map((cell) => (cell.row > row ? { ...cell, row: cell.row - 1 } : { ...cell }))
return normalize(kept, columns)
}
/** Drop empty rows and pull everything up, like "delete blank rows" in a sheet. */
export function compactCells(cells: SheetCell[], columns = GRID_COLS): SheetCell[] {
const rows = [...new Set(cells.map((cell) => cell.row))].sort((a, b) => a - b)
const map = new Map(rows.map((row, index) => [row, index + 1]))
return normalize(cells.map((cell) => ({ ...cell, row: map.get(cell.row) ?? cell.row })), columns)
}
export function removeKeys(cells: SheetCell[], keys: string[], columns = GRID_COLS): SheetCell[] {
return normalize(cells.filter((cell) => !keys.includes(cell.key)), columns)
}
/**
* Where a field will actually sit, spelled out for the inspector:
* `第 2 行 · 第 1/12 列 · 宽 6 列`, or `第 2 行 · 整行` when it spans everything.
*/
export interface PositionParts {
row: (row: number) => string
column: (start: number, total: number) => string
full: string
width: (units: number) => string
}
export function positionText(cell: SheetCell, parts: PositionParts, columns = GRID_COLS): string {
const rowText = parts.row(cell.row)
if (cell.units >= columns) return `${rowText} · ${parts.full}`
return `${rowText} · ${parts.column(cell.col, columns)} · ${parts.width(cell.units)}`
}
/** Suggest a field key that no other field in the list already uses. */
export function uniqueKey(type: string, existing: Iterable<string>): string {
const taken = new Set(existing)
const base = `field_${type}`.replace(/[^a-z0-9_]/gi, '_').toLowerCase()
if (!taken.has(base)) return base
let suffix = 2
while (taken.has(`${base}_${suffix}`)) suffix += 1
return `${base}_${suffix}`
}
/** Problems that would make the form unusable at approval time. */
const UNIT_FIELD_TYPES: string[] = ['number', 'money', 'formula']
/** `{form.x}` / `{form:x}` 里的字段名;不是这种写法回空串(与后端 quota._form_ref 同口径)。 */
function quotaFieldRef(expr: unknown): string {
const match = /^\{form[.:]([^}]+)\}$/.exec(String(expr ?? '').trim())
return match ? match[1] : ''
}
export function validateFields(fields: FormFieldDef[], columns = GRID_COLS): string[] {
const problems: string[] = []
const seen = new Map<string, number>()
// 额度配置允许往前引用后面才出现的字段,所以引用关系单独拿全量键集判
const allKeys = new Set(fields.map((item) => (item.key ?? '').trim()).filter(Boolean))
let tabsAt = 0
const needsOptions = OPTION_FIELD_TYPES
let titleAt = 0
fields.forEach((field, index) => {
const at = `第 ${index + 1} 个字段`
if (!FIELD_TYPES.includes(field.type)) problems.push(`${at}类型无效:${field.type}`)
if (field.type === 'divider') return
if (NON_INPUT_TYPES.includes(field.type) && field.required) {
problems.push(`${at}「${field.label || field.key}」只用于展示,不能设为必填`)
}
if (field.type === 'auto' && !AUTO_VALUE_KEYS.includes((field.auto ?? '') as never)) {
problems.push(`${at}「${field.label || field.key}」还没选择要带出的系统值`)
}
// 自动值的生成规则(编号前缀/日期段/位数/归零周期、时间写法、前后缀):
// 与后端 numbering.problems 同一把尺子,设计器里写歪了当场就报。
problems.push(...autoRuleProblems(field.autoRule, `第 ${index + 1} 个字段「${field.label || field.key}」的生成规则`))
// 普通字段的自动带出(申请人 / 申请部门 / 审批人…):来源写在这类字段带不出来的值上,
// 发起时那一格就是空的,条件分支和按表单找人会静默失灵,保存时先拦住。
problems.push(...autoPresetProblems(field, `第 ${index + 1} 个字段「${field.label || field.key}」`))
if (field.type === 'rate' && field.max !== undefined && (field.max < 1 || field.max > 10)) {
problems.push(`${at}「${field.label || field.key}」的评分星级要在 1-10 之间`)
}
// 文本类的字数上限与校验正则、附件类的三个限制、空白格的高度:都是"配歪了当场就该说"的,
// 口径与后端 formruntime.text_config_problems / file_config_problems 同一把尺子。
if (TEXT_LIMIT_TYPES.includes(field.type)) {
textConfigProblems(field).forEach((problem) => problems.push(`${at}「${field.label || field.key}」${problem}`))
}
if (FILE_LIMIT_TYPES.includes(field.type)) {
fileConfigProblems(field).forEach((problem) => problems.push(`${at}「${field.label || field.key}」${problem}`))
}
// 多选月份的挑选姿势:认不出的写法(手改 JSON、AI 起草)也在这一步说,别留给渲染器猜
if (field.type === 'months') {
monthsConfigProblems(field).forEach((problem) => problems.push(`${at}「${field.label || field.key}」${problem}`))
}
// 外部页面:没挑页面、参数写得这个页面用不上、内嵌框高度出格,都属于"到填单页才露出来",
// 保存这一刻说清楚。"源在不在"这里查不了(要读库),后端 formruntime.validate_schema 兜。
if (field.type === 'embed') {
embedConfigProblems(field, { fieldKeys: allKeys }).forEach((problem) =>
problems.push(`${at}「${field.label || field.key}」${problem}`)
)
}
// 标签页:一页都没有、外部页面那一页上还压着格子、页签没名字,都是"到填单页才露出来"的。
// 「一张表单只能有一个标签页」也在这里数——两个页签各切一屏,第二个人根本不知道另一页在哪儿。
if (field.type === 'tabs') {
if (tabsAt) problems.push(`标签页字段只能有一个(第 ${tabsAt} 个与第 ${index + 1} 个)`)
else tabsAt = index + 1
tabProblems(field, {
fieldKeys: allKeys,
targets: fields,
fieldCountOf: (tabKey) => fields.filter((item) => item.type !== 'tabs' && tabKeyOf(item, tabsOf(field)) === tabKey).length
}).forEach((problem) => problems.push(problem))
}
if (field.type === 'spacer' && field.height !== undefined && field.height !== null) {
const raw = Number(field.height)
if (!Number.isFinite(raw) || raw < SPACER_MIN_HEIGHT || raw > SPACER_MAX_HEIGHT) {
problems.push(`${at}「${field.label || field.key}」的空白高度要在 ${SPACER_MIN_HEIGHT}-${SPACER_MAX_HEIGHT}px 之间`)
}
}
const key = (field.key ?? '').trim()
const label = (field.label ?? '').trim()
if (!label && !LABELLESS_TYPES.includes(field.type)) problems.push(`${at}缺少字段标题`)
if (!key) {
problems.push(`${at}缺少字段名`)
} else if (seen.has(key)) {
problems.push(`字段名「${key}」重复(第 ${seen.get(key)} 个与第 ${index + 1} 个)`)
} else {
seen.set(key, index + 1)
}
// 绑了数据字典的字段以字典为选项来源,不再要求在表单里另配一份静态选项。
if (needsOptions.includes(field.type) && !(field.options ?? []).length && !(field.dictCode ?? '').trim()) {
problems.push(`${at}「${label || key}」是选项类字段,但未配置任何选项`)
}
if (field.type === 'number' && field.min !== undefined && field.max !== undefined && field.min > field.max) {
problems.push(`${at}「${label || key}」的最小值大于最大值`)
}
if (UNIT_FIELD_TYPES.includes(field.type)) {
const problem = unitProblem(field.unit)
if (problem) problems.push(`${at}「${label || key}」的单位${problem}`)
}
if (field.type === 'table') {
validateTableField({ ...field, key, label }).forEach((problem) => problems.push(`${at}${problem}`))
}
// 额度控制:金额来源与三个数的落点都得指得到真字段,配歪了保存时就挡。
// 「额度定义存不存在」这里查不了(要读库),后端 form_problems 那道闸补这一条。
const quota = field.quota
if (quota && (quota.def || (quota.amount ?? '').trim() || quota.rows)) {
const where = `${at}「${label || key}」的额度控制`
if (!(quota.def ?? '').trim()) problems.push(`${where}没选额度定义`)
// 留空 = 跟随定义,其余只认这三个值
if (quota.over && !['hard', 'soft', 'off'].includes(quota.over)) {
problems.push(`${where}的超支策略不支持:${quota.over}`)
}
const line = quota.rows
const isTable = field.type === 'table'
if (isTable && !line) {
problems.push(`${where}挂在明细表上,要写明 rows:哪一列是台账单号、哪一列是本次金额`)
}
if (!isTable && line) {
problems.push(`${where}不是明细表,用不上 rows(逐行控额度才需要它)`)
}
const amountRef = quotaFieldRef(quota.amount)
if (isTable && line) {
// 明细表那一档:引用的是列名,且三个数写在行内列上(后端拿得到定义维度,查得更细)
const columns = new Set((field.columns ?? []).map((column) => column.key))
const amountCol = (line.amount ?? '').trim()
if (!amountCol) problems.push(`${where}没写本次金额取明细表的哪一列(rows.amount)`)
const dimCols = Object.entries(line.dims ?? {}).map(
([dim, column]) => (column ?? '').trim() || dim
)
;[...dimCols, amountCol].forEach((column) => {
if (column && !columns.has(column)) problems.push(`${where}引用的明细表列不存在:「${column}」`)
})
const rowShow = line.show ?? {}
const rowTargets: string[] = []
;([['total', '借款额'], ['used', '已冲'], ['avail', '剩余']] as const).forEach(([cell, name]) => {
const target = (rowShow[cell] ?? '').trim()
if (!target) return
if (!columns.has(target)) problems.push(`${where}要把${name}写进不存在的明细列「${target}」`)
else if (target === amountCol) problems.push(`${where}不能把${name}写进本次金额那一列,否则填进去的数会被盖掉`)
else if (rowTargets.includes(target)) problems.push(`${where}把${name}和前面那列写到了同一个明细列「${target}」,会互相盖掉`)
rowTargets.push(target)
})
} else if (!isTable) {
if (!(quota.amount ?? '').trim()) {
problems.push(`${where}没写本次金额取自哪里(如 {form.amount})`)
} else if (amountRef && !allKeys.has(amountRef)) {
problems.push(`${where}的本次金额引用了不存在的字段「${amountRef}」`)
}
const dims = quota.dims ?? {}
Object.entries(dims).forEach(([dim, expr]) => {
const ref = quotaFieldRef(expr)
if (ref && !allKeys.has(ref)) problems.push(`${where}的维度「${dim}」引用了不存在的字段「${ref}」`)
})
}
const show = quota.show ?? {}
const targets: string[] = []
;([['total', '总额'], ['used', '已用'], ['avail', '剩余']] as const).forEach(([cell, name]) => {
const target = (show[cell] ?? '').trim()
if (!target) return
if (!allKeys.has(target)) problems.push(`${where}要把${name}写进不存在的字段「${target}」`)
else if (target === key) problems.push(`${where}不能把${name}写回自己,否则本次金额会被盖掉`)
else if (targets.includes(target)) problems.push(`${where}有两格写到了同一个字段「${target}」,会互相盖掉`)
targets.push(target)
})
}
if (field.type === 'formula' && !(field.formula ?? '').trim()) {
problems.push(`${at}「${label || key}」还没有填写计算公式`)
}
if (field.type === 'title') {
// 两个标题字段都说自己是标题,而 work.title 只有一个;与后端 form_problems 同口径
if (titleAt) problems.push(`流程标题字段只能有一个(第 ${titleAt} 个与第 ${index + 1} 个)`)
else titleAt = index + 1
if (field.titleMode && !['rule', 'manual'].includes(field.titleMode)) {
problems.push(`${at}「${label || key}」的标题生成方式不支持:${field.titleMode}`)
}
// 这一格自带的标题规则:选了模板/表达式却空着,后端保存时也会挡,这里先说清楚
const ruleProblem = fieldTitleRuleProblem(field.titleRule)
if (ruleProblem) problems.push(`${at}「${label || key}」的标题规则有问题:${ruleProblem}`)
}
})
if (columns !== GRID_COLS) problems.push('布局列数只支持 12 列网格')
return problems
}