feat(tenant): implement self-service tenant creation functionality

Added a new API endpoint for creating tenants, allowing any logged-in user to create their own workspace. The backend automatically assigns the creator as the Owner of the new tenant. A new CreateTenantDialog component was introduced in the frontend, enabling users to input the workspace name and an optional description. Internationalization files were updated to include relevant messages for this feature across multiple languages.

Refs: #1303
This commit is contained in:
wizardchen
2026-05-16 04:42:21 +08:00
committed by lyingbug
parent 79d397297d
commit 29dc99ae79
10 changed files with 466 additions and 29 deletions
@@ -0,0 +1,120 @@
<template>
<!-- 自助创建新工作区弹窗。任意已登录用户均可调用 POST /api/v1/tenants
(后端 router 已去掉 g.CrossTenant() 守卫),handler 会自动把当前
用户 EnsureOwner 成新租户的 Owner。提交成功后通知父组件,由父组件
决定下一步导航(一般是切到新租户)。 -->
<t-dialog
:visible="visible"
:header="$t('tenant.create.dialogTitle')"
width="480px"
:on-confirm="handleSubmit"
:on-close="handleClose"
:confirm-btn="{ content: $t('tenant.create.submit'), loading: submitting, theme: 'primary' }"
:cancel-btn="{ content: $t('tenant.create.cancel') }"
:close-on-overlay-click="!submitting"
:close-on-esc-keydown="!submitting"
@update:visible="onVisibleUpdate"
>
<t-form ref="formRef" :data="form" :rules="formRules" @submit.prevent>
<t-form-item :label="$t('tenant.create.nameLabel')" name="name">
<t-input
v-model="form.name"
:placeholder="$t('tenant.create.namePlaceholder')"
:maxlength="128"
autofocus
/>
</t-form-item>
<t-form-item :label="$t('tenant.create.descriptionLabel')" name="description">
<t-textarea
v-model="form.description"
:placeholder="$t('tenant.create.descriptionPlaceholder')"
:maxlength="512"
:autosize="{ minRows: 2, maxRows: 4 }"
/>
</t-form-item>
</t-form>
</t-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin, type FormInstanceFunctions, type FormRule } from 'tdesign-vue-next'
import { createTenant, type TenantInfo } from '@/api/tenant'
const props = defineProps<{
visible: boolean
}>()
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
// 创建成功后由父组件决定如何导航(切换到新租户、刷新本地列表等)。
(e: 'created', tenant: TenantInfo): void
}>()
const { t } = useI18n()
const formRef = ref<FormInstanceFunctions | null>(null)
const submitting = ref(false)
const form = reactive({
name: '',
description: '',
})
const formRules: Record<string, FormRule[]> = {
name: [
{ required: true, message: t('tenant.create.nameRequired'), trigger: 'blur' },
{ max: 128, message: t('tenant.create.nameRequired'), trigger: 'blur' },
],
}
// 每次打开时重置表单;关闭时不动状态,让动画结束。
watch(
() => props.visible,
(open) => {
if (open) {
form.name = ''
form.description = ''
// 等 dialog 渲染完成再清掉之前的校验态。
requestAnimationFrame(() => formRef.value?.clearValidate?.())
}
},
)
const onVisibleUpdate = (next: boolean) => {
if (!next && submitting.value) return
emit('update:visible', next)
}
const handleClose = () => {
if (submitting.value) return
emit('update:visible', false)
}
const handleSubmit = async () => {
if (submitting.value) return
const validateResult = await formRef.value?.validate?.()
if (validateResult !== true) return
submitting.value = true
try {
const response = await createTenant({
name: form.name.trim(),
description: form.description.trim() || undefined,
})
if (!response.success || !response.data) {
MessagePlugin.error(response.message || t('tenant.create.failed'))
return
}
MessagePlugin.success(t('tenant.create.success'))
emit('created', response.data)
emit('update:visible', false)
} catch (error: any) {
console.error('Failed to create tenant:', error)
MessagePlugin.error(error?.message || t('tenant.create.failed'))
} finally {
submitting.value = false
}
}
</script>
+67 -3
View File
@@ -68,11 +68,21 @@
<t-loading size="small" />
</div>
</div>
<!-- 自助创建新工作区入口:任意已登录用户可点击,后端会把当前用户
写成新租户的 Owner(见 internal/handler/tenant.go CreateTenant)。 -->
<div class="tenant-create-action" @click="openCreateDialog">
<t-icon name="add" class="tenant-create-icon" />
<span class="tenant-create-label">{{ $t('tenant.create.action') }}</span>
</div>
</div>
</Transition>
<!-- 遮罩层 -->
<div v-if="showDropdown" class="tenant-overlay" @click="closeDropdown"></div>
<!-- 创建工作区弹窗:复用共享组件,TenantSelector 与 UserMenu 都用它 -->
<CreateTenantDialog v-model:visible="createDialogVisible" @created="onTenantCreated" />
</div>
</template>
@@ -83,6 +93,7 @@ import { searchTenants, type TenantInfo } from '@/api/tenant'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
const { t } = useI18n()
const authStore = useAuthStore()
@@ -231,16 +242,38 @@ const handleSearchInput = () => {
const handleScroll = () => {
if (!tenantListRef.value) return
const { scrollTop, scrollHeight, clientHeight } = tenantListRef.value
const isNearBottom = scrollHeight - scrollTop - clientHeight < 50
if (isNearBottom && hasMore.value && !loading.value) {
currentPage.value++
loadTenants(true)
}
}
// ---- 创建新工作区 ----
// dialog 由共享组件 CreateTenantDialog 渲染,这里只负责打开 / 接收创建结果。
const createDialogVisible = ref(false)
const openCreateDialog = () => {
closeDropdown()
createDialogVisible.value = true
}
const onTenantCreated = (newTenant: TenantInfo) => {
// 把新租户合并进当前列表并切过去。和 selectTenant 走同一条链路:
// setSelectedTenant + navigateAfterTenantSwitch。后端 X-Tenant-ID 中
// 间件会查 tenant_members 校验,EnsureOwner 已经在后端写好 owner 行。
tenants.value = [newTenant, ...tenants.value.filter(t => t.id !== newTenant.id)]
total.value = total.value + 1
authStore.setAllTenants(tenants.value)
authStore.setSelectedTenant(newTenant.id, newTenant.name)
setTimeout(() => {
navigateAfterTenantSwitch()
}, 300)
}
onMounted(() => {
// 预加载租户列表
loadTenants()
@@ -517,6 +550,37 @@ onUnmounted(() => {
padding: 8px;
}
.tenant-create-action {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
margin: 4px 6px 6px;
border-top: .5px solid var(--td-component-stroke);
border-radius: 6px;
cursor: pointer;
color: var(--td-brand-color);
font-size: 13px;
font-weight: 500;
transition: background 0.15s;
&:hover {
background: rgba(7, 192, 95, 0.08);
}
}
.tenant-create-icon {
font-size: 14px;
flex-shrink: 0;
}
.tenant-create-label {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// 下拉动画
.dropdown-enter-active,
.dropdown-leave-active {
+82 -5
View File
@@ -208,8 +208,19 @@
{{ $t('tenant.switcher.empty') }}
</div>
</div>
<!-- 自助创建新工作区入口:放在租户列表底部,所有能 hover 出这个
子菜单的用户都能看到(包括单租户用户)。后端 router 已对
POST /api/v1/tenants 去掉跨租户超管守卫,handler 内部会把
当前用户 EnsureOwner 成新租户的 Owner。 -->
<div class="tenant-submenu-create" @click="openCreateTenantDialog">
<t-icon name="add" class="tenant-submenu-create-icon" />
<span class="tenant-submenu-create-label">{{ $t('tenant.create.action') }}</span>
</div>
</div>
</Teleport>
<!-- 创建工作区弹窗 -->
<CreateTenantDialog v-model:visible="createTenantDialogVisible" @created="onTenantCreated" />
</div>
</template>
@@ -222,8 +233,10 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { getCurrentUser, logout as logoutApi } from '@/api/auth'
import { useI18n } from 'vue-i18n'
import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue'
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
import { listAllIMChannels, type IMChannelOverview } from '@/api/agent'
import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'
import type { TenantInfo } from '@/api/tenant'
import { useRoleLabel, useHomeTenant } from '@/composables/useRoleLabel'
const { t } = useI18n()
@@ -350,6 +363,37 @@ const closeAll = () => {
menuVisible.value = false
}
// ---------- Create new tenant ----------
// 普通用户在租户子菜单底部点 "+ 创建新工作区" → 弹 CreateTenantDialog →
// 后端写一行 owner 的 tenant_members → 直接切到新租户。复用 switchToTenant
// 同款的 setSelectedTenant + navigateAfterTenantSwitch 链路,避免 token
// 依然指向旧租户带来的 SSE / store 不一致。
const createTenantDialogVisible = ref(false)
const openCreateTenantDialog = () => {
closeAll()
createTenantDialogVisible.value = true
}
const onTenantCreated = (newTenant: TenantInfo) => {
// memberships 由 /auth/login 落库 + localStorage 缓存。这里追加一条
// owner 进去让 hover 子菜单立即看到新租户;hard reload 后会被
// /auth/me 的真实数据覆盖,状态不会长期失真。
const next = [
...(authStore.memberships ?? []),
{
tenant_id: newTenant.id,
tenant_name: newTenant.name,
role: 'owner',
},
]
authStore.setMemberships(next)
authStore.setSelectedTenant(newTenant.id, newTenant.name)
setTimeout(() => {
navigateAfterTenantSwitch()
}, 300)
}
// ---------- Tenant switcher submenu ----------
//
// Same hover-driven submenu pattern as the IM panel above; data comes from
@@ -372,12 +416,14 @@ const switchableMemberships = computed<Membership[]>(() => {
return authStore.memberships ?? []
})
// Rendered only when there's something to switch *to*. Multi-tenant members
// (memberships.length > 1) need it for tenant switching; superusers keep
// using the sidebar TenantSelector for the "any tenant in the system" case,
// so we don't double-show the entry there.
// Rendered whenever the user has at least one membership — even single-
// tenant users need this submenu to discover the "create new workspace"
// entry at the bottom. Multi-tenant users additionally use it to switch
// between memberships. Cross-tenant superusers keep using the sidebar
// TenantSelector for the "any tenant in the system" case, so we don't
// double-show that here.
const showTenantSwitcher = computed(() => {
return switchableMemberships.value.length > 1
return switchableMemberships.value.length >= 1
})
const isCurrentTenant = (id: number) => {
@@ -1234,5 +1280,36 @@ onUnmounted(() => {
font-size: 12px;
color: var(--td-text-color-placeholder);
}
.tenant-submenu-create {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
margin: 4px 6px 6px;
border-top: .5px solid var(--td-component-stroke);
border-radius: 6px;
cursor: pointer;
color: var(--td-brand-color);
font-size: 13px;
font-weight: 500;
transition: background 0.15s;
&:hover {
background: rgba(7, 192, 95, 0.08);
}
.tenant-submenu-create-icon {
font-size: 14px;
flex-shrink: 0;
}
.tenant-submenu-create-label {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
</style>