feat(invitations): implement pending invitations feature with polling and dialog

Added functionality for managing pending invitations, including a polling mechanism to update the invitation count in real-time. Introduced a new dialog component for users to view and respond to their invitations without navigating away from their current context. Updated API endpoints for fetching and managing invitations, and enhanced the user interface with relevant internationalization support.

Refs: #1303
This commit is contained in:
wizardchen
2026-05-17 21:19:59 +08:00
committed by lyingbug
parent 3bb0d6d763
commit 884ac44283
36 changed files with 4378 additions and 440 deletions
@@ -0,0 +1,325 @@
<template>
<!-- "My invitations" inbox as a dialog. The previous version of
this was a full /platform/invitations route, but the inbox is
intrinsically transient — open it, act, dismiss — and a modal
keeps the user in whatever context the bell icon was clicked
from rather than yanking them to a separate page. The trigger
lives in UserMenu's avatar-row bell. -->
<t-dialog v-model:visible="visibleModel" :header="$t('tenantInvitation.myInbox.title')" :footer="false" width="540px"
:close-on-overlay-click="true">
<p class="my-invitations-desc">{{ $t('tenantInvitation.myInbox.description') }}</p>
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
<span>{{ $t('tenantMember.loading') }}</span>
</div>
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
<t-button size="small" @click="reload">{{ $t('tenantMember.retry') }}</t-button>
</template>
</t-alert>
</div>
<div v-else-if="invitations.length === 0" class="empty-state">
<t-empty :description="$t('tenantInvitation.myInbox.empty')" />
</div>
<ul v-else class="invitation-list">
<li v-for="row in invitations" :key="row.id" class="invitation-card">
<div class="invitation-card-main">
<div class="invitation-card-header">
<span class="tenant-name">
{{ row.tenant_name || $t('tenantInvitation.myInbox.tenantLabel') + ' #' + row.tenant_id }}
</span>
<t-tag :theme="roleTagTheme(row.role)" size="small">
{{ $t('tenantMember.role.' + row.role) }}
</t-tag>
</div>
<div class="invitation-card-meta">
<span class="meta-row">
<t-icon name="user" size="14px" class="meta-icon" />
<span class="meta-label">{{ $t('tenantInvitation.myInbox.from') }}:</span>
<span class="meta-value">{{ inviterDisplay(row) }}</span>
</span>
<span class="meta-row">
<t-icon name="time" size="14px" class="meta-icon" />
<span class="meta-value">
{{ $t('tenantInvitation.myInbox.expiresIn', { date: formatDate(row.expires_at) }) }}
</span>
</span>
<span v-if="row.message" class="meta-row meta-row--message">
<t-icon name="chat" size="14px" class="meta-icon" />
<span class="meta-label">{{ $t('tenantInvitation.myInbox.messageLabel') }}:</span>
<span class="meta-value">{{ row.message }}</span>
</span>
</div>
</div>
<div class="invitation-card-actions">
<t-button theme="primary" size="small" :loading="acting === row.id" @click="onAccept(row)">
{{ $t('tenantInvitation.myInbox.acceptButton') }}
</t-button>
<t-button theme="default" variant="outline" size="small" :loading="acting === row.id" @click="onDecline(row)">
{{ $t('tenantInvitation.myInbox.declineButton') }}
</t-button>
</div>
</li>
</ul>
</t-dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import {
listMyInvitations,
acceptInvitation,
declineInvitation,
type TenantInvitation,
} from '@/api/tenant/invitations'
import type { TenantRole } from '@/api/tenant/members'
// v-model:visible — the parent (UserMenu) owns the open/close state
// so the bell icon stays the single source of truth. Reload is run
// on every open transition so the list reflects accept/decline
// actions taken in another tab while the dialog was closed.
const props = defineProps<{ visible: boolean }>()
const emit = defineEmits<{ (e: 'update:visible', v: boolean): void }>()
const visibleModel = computed({
get: () => props.visible,
set: (v) => emit('update:visible', v),
})
const { t, locale } = useI18n()
const authStore = useAuthStore()
const invitations = ref<TenantInvitation[]>([])
const loading = ref(false)
const error = ref('')
const acting = ref<number | null>(null)
function roleTagTheme(role: TenantRole): 'primary' | 'warning' | 'success' | 'default' {
switch (role) {
case 'owner':
return 'primary'
case 'admin':
return 'warning'
case 'contributor':
return 'success'
default:
return 'default'
}
}
function inviterDisplay(row: TenantInvitation): string {
return row.inviter_name?.trim() || row.inviter_email?.trim() || row.invited_by || '—'
}
function formatDate(s: string): string {
if (!s) return '-'
try {
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(s))
} catch {
return s
}
}
async function reload() {
loading.value = true
error.value = ''
try {
const resp = await listMyInvitations()
if (resp.success && resp.data) {
invitations.value = resp.data.invitations
authStore.setPendingInvitationCount(
invitations.value.filter((i) => i.status === 'pending').length,
)
} else {
error.value = resp.message || t('tenantInvitation.errors.generic')
}
} catch (err: any) {
error.value = err?.message || t('tenantInvitation.errors.generic')
} finally {
loading.value = false
}
}
async function onAccept(row: TenantInvitation) {
acting.value = row.id
try {
const resp = await acceptInvitation(row.id)
if (resp.success) {
invitations.value = invitations.value.filter((x) => x.id !== row.id)
authStore.setPendingInvitationCount(Math.max(0, authStore.pendingInvitationCount - 1))
await authStore.refreshFromAuthMe()
MessagePlugin.success(
t('tenantInvitation.myInbox.acceptSuccess', {
tenant: row.tenant_name || `#${row.tenant_id}`,
}),
)
} else {
MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
}
} catch (err: any) {
const status = err?.status
if (status === 404) MessagePlugin.error(t('tenantInvitation.errors.notFound'))
else if (status === 403) MessagePlugin.error(t('tenantInvitation.errors.forbidden'))
else if (status === 409) MessagePlugin.error(err?.message || t('tenantInvitation.errors.notPending'))
else MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
} finally {
acting.value = null
}
}
async function onDecline(row: TenantInvitation) {
acting.value = row.id
try {
const resp = await declineInvitation(row.id)
if (resp.success) {
invitations.value = invitations.value.filter((x) => x.id !== row.id)
authStore.setPendingInvitationCount(Math.max(0, authStore.pendingInvitationCount - 1))
MessagePlugin.success(t('tenantInvitation.myInbox.declineSuccess'))
} else {
MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
}
} catch (err: any) {
const status = err?.status
if (status === 404) MessagePlugin.error(t('tenantInvitation.errors.notFound'))
else if (status === 403) MessagePlugin.error(t('tenantInvitation.errors.forbidden'))
else if (status === 409) MessagePlugin.error(err?.message || t('tenantInvitation.errors.notPending'))
else MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
} finally {
acting.value = null
}
}
// Refetch on every open. Costs one round-trip but the user clicked
// here specifically to see the latest state; serving stale data
// would only confuse the empty-state vs "1 invitation" cases.
watch(
() => props.visible,
(v) => {
if (v) reload()
},
)
</script>
<style lang="less" scoped>
.my-invitations-desc {
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 1.55;
margin: 0 0 16px 0;
}
.loading-inline,
.error-inline {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 0;
}
.empty-state {
padding: 16px 0 8px;
display: flex;
justify-content: center;
}
.invitation-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 10px;
/* Cap height so a user with many invitations can scroll within
the dialog rather than the dialog growing past the viewport. */
max-height: 60vh;
overflow-y: auto;
}
.invitation-card {
display: flex;
align-items: stretch;
gap: 12px;
padding: 12px 14px;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
.invitation-card-main {
flex: 1 1 auto;
min-width: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.invitation-card-header {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
.tenant-name {
font-size: 14px;
font-weight: 600;
color: var(--td-text-color-primary);
}
}
.invitation-card-meta {
display: flex;
flex-direction: column;
gap: 3px;
color: var(--td-text-color-secondary);
font-size: 12px;
.meta-row {
display: inline-flex;
align-items: center;
gap: 4px;
.meta-icon {
color: var(--td-text-color-placeholder);
flex-shrink: 0;
}
.meta-value {
color: var(--td-text-color-primary);
}
&--message {
align-items: flex-start;
.meta-icon {
margin-top: 2px;
}
.meta-value {
word-break: break-word;
}
}
}
}
.invitation-card-actions {
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: center;
gap: 6px;
flex-shrink: 0;
}
}
</style>
+16 -31
View File
@@ -16,37 +16,21 @@
<span class="dropdown-title">{{ $t('tenant.switchTenant') }}</span>
<div class="search-box">
<t-icon name="search" class="search-icon" />
<input
ref="searchInput"
v-model="searchQuery"
type="text"
:placeholder="$t('tenant.searchPlaceholder')"
class="search-input"
@keydown.esc="closeDropdown"
@input="handleSearchInput"
/>
<t-icon
v-if="searchQuery"
name="close-circle-filled"
class="clear-icon"
@click="clearSearch"
/>
<input ref="searchInput" v-model="searchQuery" type="text" :placeholder="$t('tenant.searchPlaceholder')"
class="search-input" @keydown.esc="closeDropdown" @input="handleSearchInput" />
<t-icon v-if="searchQuery" name="close-circle-filled" class="clear-icon" @click="clearSearch" />
</div>
</div>
<div class="tenant-list" ref="tenantListRef" @scroll="handleScroll">
<div v-if="loading && tenants.length === 0" class="tenant-loading">
<t-loading size="small" />
<span>{{ $t('tenant.loading') }}</span>
</div>
<template v-else-if="tenants.length > 0">
<div
v-for="tenant in tenants"
:key="tenant.id"
:class="['tenant-item', { selected: isSelected(tenant.id) }]"
@click="selectTenant(tenant.id)"
>
<div v-for="tenant in tenants" :key="tenant.id"
:class="['tenant-item', { selected: isSelected(tenant.id) }]" @click="selectTenant(tenant.id)">
<div class="tenant-item-content">
<div class="tenant-item-avatar" :class="{ active: isSelected(tenant.id) }">
{{ tenant.name.charAt(0).toUpperCase() }}
@@ -59,11 +43,11 @@
<t-icon v-if="isSelected(tenant.id)" name="check" size="16px" class="check-icon" />
</div>
</template>
<div v-else class="tenant-empty">
<span>{{ $t('tenant.noMatch') }}</span>
</div>
<div v-if="loading && tenants.length > 0" class="tenant-loading-more">
<t-loading size="small" />
</div>
@@ -189,25 +173,25 @@ const selectTenant = (tenantId: number) => {
const loadTenants = async (append = false) => {
if (loading.value) return
loading.value = true
try {
const keyword = searchQuery.value.trim()
let tenantID: number | undefined = undefined
// 如果是纯数字,同时作为 tenant_id 和 keyword 搜索
// 这样既能精确匹配租户ID,也能模糊匹配名称中包含数字的租户
if (keyword && /^\d+$/.test(keyword)) {
tenantID = Number(keyword)
}
const response = await searchTenants({
keyword: keyword || undefined,
tenant_id: tenantID,
page: currentPage.value,
page_size: pageSize.value
})
if (response.success && response.data) {
if (append) {
tenants.value = [...tenants.value, ...response.data.items]
@@ -231,7 +215,7 @@ const handleSearchInput = () => {
if (searchTimer.value) {
clearTimeout(searchTimer.value)
}
searchTimer.value = window.setTimeout(() => {
currentPage.value = 1
tenants.value = []
@@ -261,13 +245,14 @@ const openCreateDialog = () => {
createDialogVisible.value = true
}
const onTenantCreated = (newTenant: TenantInfo) => {
const onTenantCreated = async (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)
await authStore.refreshFromAuthMe()
authStore.setSelectedTenant(newTenant.id, newTenant.name)
setTimeout(() => {
navigateAfterTenantSwitch()
+92 -20
View File
@@ -24,6 +24,19 @@
<div class="user-email">{{ userEmail }}</div>
</template>
</div>
<!-- Pending-invitations bell. Sits in the trailing-icon slot
of the avatar row (visually similar to a "升级/store" CTA
icon in other products). Only renders when there is at
least one pending invitation so the row stays minimal in
the common empty-inbox case. Click-stop so the dropdown
doesn't open along with the navigation. -->
<t-badge v-if="pendingInvitationCount > 0" :count="pendingInvitationCount" :max-count="99" :offset="[6, 4]"
class="user-inbox-badge-wrap">
<button type="button" class="user-inbox-btn" :title="$t('tenantInvitation.inboxTooltip')"
@click.stop="goToInvitations">
<t-icon name="notification" size="18px" />
</button>
</t-badge>
<t-icon :name="menuVisible ? 'chevron-up' : 'chevron-down'" class="dropdown-icon" />
</template>
</div>
@@ -162,8 +175,8 @@
</Teleport>
<!-- Tenant switcher floating panel — shares the same teleport rationale
as the IM submenu. Lists every tenant the user is an active member
of (from the JWT-issued memberships claim cached in authStore). -->
as the IM submenu. Data comes from authStore.memberships, kept fresh via
GET /auth/me when the submenu opens (throttled) and after invite/create. -->
<Teleport to="body">
<div v-if="tenantSubmenuOpen" class="tenant-submenu-floating" :style="tenantSubmenuStyle"
@mouseenter="showTenantSubmenu" @mouseleave="scheduleHideTenantSubmenu">
@@ -218,6 +231,7 @@
<!-- 创建工作区弹窗 -->
<CreateTenantDialog v-model:visible="createTenantDialogVisible" @created="onTenantCreated" />
<MyInvitationsDialog v-model:visible="invitationsDialogVisible" />
</div>
</template>
@@ -231,6 +245,7 @@ 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 MyInvitationsDialog from '@/components/MyInvitationsDialog.vue'
import { listAllIMChannels, type IMChannelOverview } from '@/api/agent'
import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'
import type { TenantInfo } from '@/api/tenant'
@@ -312,6 +327,25 @@ const toggleMenu = () => {
menuVisible.value = !menuVisible.value
}
// Pending invitation count surfaced as the trailing bell on the
// avatar row. Reads directly from the auth store so the App.vue
// poller and any local accept/decline updates flow through here
// without a separate fetch. The visual badge cap (99+) is handled
// by t-badge's max-count, so we just expose the raw count.
const pendingInvitationCount = computed(() => authStore.pendingInvitationCount)
// Clicking the bell opens the invitations dialog inline. Previously
// this navigated to /platform/invitations, but the inbox is short-
// lived ("see what's pending, accept or decline, dismiss") and a
// dialog keeps the user in whatever context they came from. We
// also close the avatar dropdown if it's open so the modal doesn't
// fight with a stale hover panel.
const invitationsDialogVisible = ref(false)
const goToInvitations = () => {
menuVisible.value = false
invitationsDialogVisible.value = true
}
// 快捷导航到设置的特定部分
const handleQuickNav = (section: string) => {
menuVisible.value = false
@@ -373,19 +407,8 @@ const openCreateTenantDialog = () => {
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)
const onTenantCreated = async (newTenant: TenantInfo) => {
await authStore.refreshFromAuthMe()
authStore.setSelectedTenant(newTenant.id, newTenant.name)
setTimeout(() => {
navigateAfterTenantSwitch()
@@ -395,11 +418,11 @@ const onTenantCreated = (newTenant: TenantInfo) => {
// ---------- Tenant switcher submenu ----------
//
// Same hover-driven submenu pattern as the IM panel above; data comes from
// authStore.memberships (populated by /auth/login). PR 4 of #1303 relaxed
// the X-Tenant-ID gate in middleware/auth.go to accept active membership
// rows, so flipping authStore.selectedTenantId here is enough — the next
// page reload re-issues every request with the new header and the server
// resolves the role server-side.
// authStore.memberships (refreshed from /auth/me when the submenu opens and
// after membership-changing actions). PR 4 of #1303 relaxed the X-Tenant-ID
// gate in middleware/auth.go to accept active membership rows, so flipping
// authStore.selectedTenantId here is enough — the next page reload re-issues
// every request with the new header and the server resolves the role server-side.
type Membership = {
tenant_id: number
tenant_name?: string
@@ -463,6 +486,9 @@ const switchToTenant = (m: Membership) => {
}, 400)
}
let lastTenantSubmenuMembershipRefresh = 0
const TENANT_SUBMENU_MEMBERSHIP_REFRESH_MS = 2000
const showTenantSubmenu = () => {
if (tenantSubmenuHideTimer) {
clearTimeout(tenantSubmenuHideTimer)
@@ -471,6 +497,11 @@ const showTenantSubmenu = () => {
positionTenantSubmenu()
tenantSubmenuOpen.value = true
clampFloatingToViewport('.tenant-submenu-floating', tenantSubmenuStyle)
const now = Date.now()
if (now - lastTenantSubmenuMembershipRefresh >= TENANT_SUBMENU_MEMBERSHIP_REFRESH_MS) {
lastTenantSubmenuMembershipRefresh = now
void authStore.refreshFromAuthMe()
}
}
const scheduleHideTenantSubmenu = () => {
@@ -640,6 +671,10 @@ const loadUserInfo = async () => {
updated_at: response.data.tenant.updated_at
})
}
const membershipsSync = response.data.memberships
if (Array.isArray(membershipsSync)) {
authStore.setMemberships(membershipsSync)
}
}
} catch (error) {
console.error('Failed to load user info:', error)
@@ -818,6 +853,43 @@ onUnmounted(() => {
transition: transform 0.2s;
}
/* Pending-invitations bell, sits between user-info and the chevron.
The button itself is a transparent 28x28 click target sized to
match the avatar row's other trailing affordances; t-badge wraps
it and positions its own counter pill in the top-right via the
:offset prop, so we don't try to recreate badge positioning here. */
.user-inbox-badge-wrap {
display: inline-flex;
align-items: center;
margin: 0 2px;
flex-shrink: 0;
}
.user-inbox-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: none;
border-radius: 8px;
background: transparent;
color: var(--td-text-color-secondary);
cursor: pointer;
transition: background-color 0.18s ease, color 0.18s ease;
&:hover {
background-color: var(--td-bg-color-secondarycontainer);
color: var(--td-brand-color);
}
&:focus-visible {
outline: 2px solid var(--td-brand-color-focus);
outline-offset: 1px;
}
}
.user-dropdown {
position: absolute;
bottom: 100%;