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

97 lines
3.7 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.

/**
* 表单「部门选择」字段的下拉候选项。
*
* /org/units/simple 回的是一串按 (order_number, hub_org_id, name) 排好的**平铺**部门,
* 层级只藏在 path 里(`紫光汇智\方案系统事业部\交付运维科`)。直接把它铺进下拉,
* 看到的就是名称序的一维清单:父部门排在自家子部门后面、三级科夹在二级部中间,
* 整张组织树读不出来。这里按树的前序重排,并把层级和父路径一并标出来。
*
* 缩进不写进 label:label 还要给选中态、只读回显和搜索用,前面塞空格会一路漏到那些地方。
* level / description 只是给 Select 排版和搜索用的附加信息。
*/
import type { SimpleUnit } from '@/types'
/** 部门下拉里的一行。value 仍然是后端那套不带结尾反斜杠的部门路径,存法不变。 */
export interface DeptOption {
value: string
label: string
/** 在组织树里的深度,根部门是 0;Select 按它缩进。 */
level: number
/** 去掉自身的父路径(`紫光汇智 / 方案系统事业部`),搜索筛掉父级时用来补上下文。根部门为空。 */
description: string
/** Select 的候选项类型带索引签名,这里跟着放开一条,否则整个数组传不进下拉。 */
[key: string]: unknown
}
const SEPARATOR = '\\'
/** 只用于展示父路径,跟存储口径无关。 */
const JOINER = ' / '
/** `紫光汇智\方案系统事业部\` -> ['紫光汇智','方案系统事业部'];空段一律丢掉。 */
function pathParts(path: string | undefined): string[] {
return String(path ?? '').split(SEPARATOR).filter(Boolean)
}
/** 再往上一层:`A\B\C` -> `A\B`,`A` -> ''。 */
function parentOfKey(key: string): string {
const cut = key.lastIndexOf(SEPARATOR)
return cut > 0 ? key.slice(0, cut) : ''
}
interface Entry {
key: string
parts: string[]
label: string
}
/**
* 组织树的先序序列:父部门紧跟着自己的子部门,同层保持接口回的原序。
*
* 中间层可能被停用、或被关键字筛掉,这时往上找第一个还在的祖先当父级,
* 实在没有就当根;层级取「path 真实深度」和「接上的父级 + 1」里更大的那个,
* 既不谎报深浅,也不会出现子比父浅。
*/
export function buildDeptOptions(units: SimpleUnit[]): DeptOption[] {
const entries: Entry[] = []
const index = new Map<string, number>()
for (const unit of units ?? []) {
const parts = pathParts(unit.path)
if (!parts.length) continue
const key = parts.join(SEPARATOR)
// 同路径的重复部门只留第一条:下拉里不该出现两条点起来一模一样的选项。
if (index.has(key)) continue
index.set(key, entries.length)
entries.push({ key, parts, label: unit.name || parts[parts.length - 1] })
}
const children = new Map<string, string[]>()
const roots: string[] = []
for (const entry of entries) {
let ancestor = parentOfKey(entry.key)
while (ancestor && !index.has(ancestor)) ancestor = parentOfKey(ancestor)
if (!ancestor) {
roots.push(entry.key)
continue
}
const list = children.get(ancestor) ?? []
list.push(entry.key)
children.set(ancestor, list)
}
const out: DeptOption[] = []
// parentOfKey 只会越跳越短,父子不可能成环,所以这里不用防重入。
const walk = (key: string, floor: number) => {
const entry = entries[index.get(key) as number]
const level = Math.max(entry.parts.length - 1, floor)
out.push({
value: entry.key,
label: entry.label,
level,
description: entry.parts.slice(0, -1).join(JOINER)
})
for (const child of children.get(key) ?? []) walk(child, level + 1)
}
for (const root of roots) walk(root, 0)
return out
}