Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions ui/src/views/system/identity/users/components/UserGroupSetting.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { ListItem } from '@/api/types'
import type { CascaderNode, CascaderOption, CascaderProps } from 'element-plus'
Expand All @@ -10,6 +10,7 @@ defineOptions({ name: 'UserGroupSetting' })

const { t } = useI18n({ useScope: 'global' })
const { auth } = useStore()
const usesDefaultWorkspace = computed(() => auth.isCE || auth.isPE)

const props = defineProps<{ workspaceIds: string[]; workspaceOptions: ListItem[] }>()

Expand Down Expand Up @@ -43,18 +44,19 @@ function loadWorkspaceUserGroups(node: CascaderNode, resolve: (options: Cascader
getWorkspaceUserGroups(String(node.value)).then(resolve).catch(reject)
}

// 社区版直接加载默认空间用户组;商业版编辑态预加载以完成名称回显。
// 社区版和专业版直接加载默认工作空间用户组;级联选择在编辑时预加载以回显名称。
function refreshUserGroupOptions() {
if (!props.workspaceIds.length) {
userGroupIds.value = []
userGroupOptions.value = []
return
}

const preloadRequest = auth.isCE || userGroupIds.value?.length ? Promise.all(props.workspaceIds.map(getWorkspaceUserGroups)) : Promise.resolve([])
const preloadRequest =
usesDefaultWorkspace.value || userGroupIds.value?.length ? Promise.all(props.workspaceIds.map(getWorkspaceUserGroups)) : Promise.resolve([])

preloadRequest.then((workspaceUserGroups) => {
userGroupOptions.value = auth.isCE
userGroupOptions.value = usesDefaultWorkspace.value
? workspaceUserGroups.flat()
: props.workspaceOptions
.filter(({ id }) => props.workspaceIds.includes(id))
Expand All @@ -65,16 +67,24 @@ function refreshUserGroupOptions() {
})
}

watch([() => props.workspaceIds, () => props.workspaceOptions, () => auth.isCE], refreshUserGroupOptions, { deep: true, immediate: true })
watch([() => props.workspaceIds, () => props.workspaceOptions, usesDefaultWorkspace], refreshUserGroupOptions, { deep: true, immediate: true })
</script>

<template>
<el-form-item>
<!-- 社区版直接多选用户组 -->
<el-select v-if="auth.isCE" v-model="userGroupIds" class="w-full" multiple clearable filterable :placeholder="t('userGroup.placeholder')">
<!-- 社区版和专业版直接多选用户组 -->
<el-select
v-if="usesDefaultWorkspace"
v-model="userGroupIds"
class="w-full"
multiple
clearable
filterable
:placeholder="t('userGroup.placeholder')"
>
<el-option v-for="userGroup in userGroupOptions" :key="userGroup.id" :label="userGroup.name" :value="userGroup.id" />
</el-select>
<!-- 非社区版按工作空间选择用户组 -->
<!-- 按工作空间级联选择用户组 -->
<el-cascader
v-else
v-model="userGroupIds"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The refactor is conceptually sound (replacing a duplicated auth.isCE check with a single computed), but there are a few behavioural risks and one apparent runtime bug worth checking before merging.


🔴 Potential bugs / irregularities

1. reject is not defined in loadWorkspaceUserGroups

function loadWorkspaceUserGroups(node: CascaderNode, resolve: (options: CascaderOption[]) => void) {
  getWorkspaceUserGroups(String(node.value)).then(resolve).catch(reject)
}

resolve is a parameter, but reject is not declared anywhere in scope. If the request fails, this throws ReferenceError: reject is not defined inside the promise chain (unhandled rejection). The cascader's resolve API also has no reject counterpart — you must always call resolve(...), even on failure:

getWorkspaceUserGroups(String(node.value))
  .then(resolve)
  .catch(() => resolve([]))

(Pre-existing, but it is in the shown diff and will bite you.)

2. isPE ⇒ "default workspace" is an assumption that needs product confirmation

const usesDefaultWorkspace = computed(() => auth.isCE || auth.isPE)

The whole v-if/v-else branch (multi-select vs. cascader) now hinges on this. If the professional edition can have multiple workspaces, this will:

  • hide the workspace cascader the user needs,
  • and in refreshUserGroupOptions it will do workspaceUserGroups.flat() over all props.workspaceIds, mixing groups from different workspaces into one flat multi-select with no provenance.

Please verify the PE data model. If PE is not strictly single/default-workspace, the predicate is a misnomer and a logic regression. Consider naming it after the actual condition (hasSingleWorkspace, isDefaultWorkspaceEdition) so the intent is unambiguous.

3. The else branch assigns workspace options to userGroupOptions

userGroupOptions.value = usesDefaultWorkspace.value
  ? workspaceUserGroups.flat()
  : props.workspaceOptions.filter(({ id }) => props.workspaceIds.includes(id))

userGroupOptions is only bound to the <el-select>, which is only rendered when usesDefaultWorkspace is true. So in the else branch you're populating a user-group list with workspace objects — at best dead code, at worst a wrong-type value that leaks if the edition ever flips at runtime. Pre-existing, but the refactor is a good moment to clean it up (or confirm it feeds the cascader's name-echo path).

4. Race condition on rapid prop changes

refreshUserGroupOptions fires an async Promise.all(...).then(...) with no request token / abort. If workspaceIds changes twice quickly (very likely with deep: true + immediate: true during parent mount), a stale response can overwrite the fresh one. Suggest a simple sequence guard:

let reqId = 0
function refreshUserGroupOptions() {
  const id = ++reqId
  ...
  preloadRequest.then((groups) => {
    if (id !== reqId) return
    ...
  })
}

5. Stale userGroupIds when the edition/branch flips

Switching between el-select and el-cascader unmounts the input, but userGroupIds is not reset. Default-workspace group IDs are not valid cascader paths (and vice-versa). Add a reset (or validation) when usesDefaultWorkspace transitions.


🟡 Optimization suggestions

6. deep: true is heavier than needed here

watch([() => props.workspaceIds, () => props.workspaceOptions, usesDefaultWorkspace], refreshUserGroupOptions, { deep: true, immediate: true })

props.workspaceIds and props.workspaceOptions are replaced wholesale by the parent (typical Vue pattern); you rarely mutate them in place. deep: true forces a full recursive traversal of workspaceOptions on every watch evaluation, for a callback that only needs the array identity and id members. Prefer:

watch(
  [() => props.workspaceIds, () => props.workspaceOptions, usesDefaultWorkspace],
  refreshUserGroupOptions,
  { immediate: true, flush: 'post' }
)

or, if in-place mutation really happens, use a shallow signature like () => props.workspaceIds.join(',').

Also consider flush: 'post' so the request isn't fired mid-render during parent mount.

7. The preload ternary should be parenthesized

const preloadRequest =
  usesDefaultWorkspace.value || userGroupIds.value?.length ? Promise.all(...) : Promise.resolve([])

Precedence is correct (|| binds tighter than ?:), but the line-break makes it easy to misread. Either extract:

const shouldPreload = usesDefaultWorkspace.value || userGroupIds.value.length > 0
const preloadRequest = shouldPreload
  ? Promise.all(props.workspaceIds.map(getWorkspaceUserGroups))
  : Promise.resolve([])

or add explicit parens.

8. userGroupIds.value?.length — optional chain is redundant

If userGroupIds is ref<string[]>([]), .value is never nullish; drop the ?. (or type it as nullable if it really can be). Minor readability win.

9. Promise.all fans out one request per workspace with no dedupe/batching

For N workspaces this is N round-trips. If a batch endpoint exists (getUserGroupsByWorkspaces(ids)), prefer it; otherwise at least dedupe props.workspaceIds.

10. computed on a store getter — verify reactivity

auth.isCE || auth.isPE only re-evaluates if both flags are reactive (Pinia getters or refs). If isPE is a plain property set once at bootstrap, the computed is fine but the watch will never fire on edition change — in which case it should be a const outside the component instead of a computed. Worth confirming.


🟢 Nits

  • Template reformat of <el-select> to multi-line is fine; no functional change.
  • Comment rewording is accurate but now says "级联选择在编辑时预加载" — note the preload also happens when userGroupIds.value.length > 0 in non-edit states; the comment slightly overstates.
  • CascaderProps is imported but not used anywhere in the shown hunks — confirm it's used further down or drop it (dead import will be flagged by lint if no-unused-vars covers types).
  • Consider extracting the "should I use the flat default-workspace list" predicate into a well-named helper and reusing it in both the watch and the template so the two can't drift apart again.

Expand Down
Loading