Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

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

wizardchen884ac44283fc
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index aa40b0c89..79c69773d 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, nextTick, onMounted, onUnmounted } from 'vue'
+import { computed, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
@@ -145,6 +145,43 @@ const handleGlobalOIDCCallback = async () => {
let updateCheckTimer: ReturnType<typeof setInterval> | null = null
+// Pending invitations poll: fires once on mount (logged-in case) and
+// then every 2 minutes. Light enough to keep the avatar-row badge
+// near-live without slamming the API, and avoids the cost of a
+// dedicated SSE/WebSocket connection. Stopped on logout via the
+// computed below.
+let invitationPollTimer: ReturnType<typeof setInterval> | null = null
+const INVITATION_POLL_INTERVAL_MS = 2 * 60 * 1000
+
+const startInvitationPolling = () => {
+ if (invitationPollTimer || !authStore.isLoggedIn) return
+ // Immediate fetch so the badge is correct before the first tick.
+ authStore.fetchPendingInvitationCount()
+ invitationPollTimer = setInterval(() => {
+ if (!authStore.isLoggedIn) return
+ authStore.fetchPendingInvitationCount()
+ }, INVITATION_POLL_INTERVAL_MS)
+}
+
+const stopInvitationPolling = () => {
+ if (invitationPollTimer) {
+ clearInterval(invitationPollTimer)
+ invitationPollTimer = null
+ }
+}
+
+// React to login/logout via the store's isLoggedIn computed. Watching
+// here (rather than only on first mount) handles the OIDC callback
+// flow where the user logs in well after App.vue has already mounted.
+watch(
+ () => authStore.isLoggedIn,
+ (logged) => {
+ if (logged) startInvitationPolling()
+ else stopInvitationPolling()
+ },
+ { immediate: true },
+)
+
onMounted(() => {
handleGlobalOIDCCallback()
@@ -175,6 +212,7 @@ onUnmounted(() => {
if (updateCheckTimer) {
clearInterval(updateCheckTimer)
}
+ stopInvitationPolling()
})
</script>
@@ -188,29 +226,29 @@ onUnmounted(() => {
</template>
<style>
html {
- /* 提示 UA 使用对应配色绘制滚动条等,减少主题切换时的额外重绘 */
- color-scheme: light dark;
+ /* 提示 UA 使用对应配色绘制滚动条等,减少主题切换时的额外重绘 */
+ color-scheme: light dark;
}
body,
html,
#app {
- width: 100%;
- height: 100%;
- margin: 0;
- padding: 0;
- font-size: 14px;
- font-family: var(--app-font-family);
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- background: var(--td-bg-color-page);
- color: var(--td-text-color-primary);
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ font-size: 14px;
+ font-family: var(--app-font-family);
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ background: var(--td-bg-color-page);
+ color: var(--td-text-color-primary);
}
#app {
- /* 独立合成层,减轻 WebKit 全量重绘时整窗与内容的撕裂感(桌面 WebView 尤其明显) */
- isolation: isolate;
- transform: translateZ(0);
- backface-visibility: hidden;
+ /* 独立合成层,减轻 WebKit 全量重绘时整窗与内容的撕裂感(桌面 WebView 尤其明显) */
+ isolation: isolate;
+ transform: translateZ(0);
+ backface-visibility: hidden;
}
</style>
diff --git a/frontend/src/api/tenant/invitations.ts b/frontend/src/api/tenant/invitations.ts
new file mode 100644
index 000000000..eda2aa2ce
--- /dev/null
+++ b/frontend/src/api/tenant/invitations.ts
@@ -0,0 +1,193 @@
+import { get, post, del } from '@/utils/request'
+import type { TenantRole } from '@/api/tenant/members'
+
+// TenantInvitationStatus mirrors internal/types/tenant_invitation.go's
+// five-state machine. pending is the only non-terminal state; the rest
+// are recorded for the audit trail.
+export type TenantInvitationStatus =
+ | 'pending'
+ | 'accepted'
+ | 'declined'
+ | 'revoked'
+ | 'expired'
+
+// TenantInvitation is the API projection of a tenant_invitations row,
+// hydrated with the inviter / invitee user fields and the tenant name
+// when the backend has them. Missing optional fields render as the
+// raw id in the UI rather than dropping the row.
+export interface TenantInvitation {
+ id: number
+ tenant_id: number
+ tenant_name?: string
+ invitee_user_id: string
+ invitee_email?: string
+ invitee_name?: string
+ invited_by?: string | null
+ inviter_email?: string
+ inviter_name?: string
+ role: TenantRole
+ status: TenantInvitationStatus
+ message?: string
+ expires_at: string
+ responded_at?: string | null
+ created_at: string
+}
+
+export interface ListInvitationsResponse {
+ success: boolean
+ data?: {
+ invitations: TenantInvitation[]
+ total: number
+ page?: number
+ page_size?: number
+ }
+ message?: string
+}
+
+export interface ListTenantInvitationsParams {
+ includeTerminal?: boolean
+ page?: number
+ page_size?: number
+}
+
+function buildTenantInvitationsQuery(options: ListTenantInvitationsParams): string {
+ const u = new URLSearchParams()
+ if (options.includeTerminal) u.set('include_terminal', 'true')
+ if (options.page != null && options.page > 0) u.set('page', String(options.page))
+ if (options.page_size != null && options.page_size > 0) u.set('page_size', String(options.page_size))
+ const qs = u.toString()
+ return qs ? `?${qs}` : ''
+}
+
+export interface CreateInvitationRequest {
+ email: string
+ role: TenantRole
+ message?: string
+}
+
+export interface CreateInvitationResponse {
+ success: boolean
+ data?: TenantInvitation
+ message?: string
+}
+
+export interface SimpleResponse {
+ success: boolean
+ message?: string
+}
+
+export interface AcceptInvitationResponse {
+ success: boolean
+ data?: {
+ membership: {
+ tenant_id: number
+ role: TenantRole
+ status: string
+ joined_at: string
+ }
+ }
+ message?: string
+}
+
+export interface PendingCountResponse {
+ success: boolean
+ data?: { pending_count: number }
+ message?: string
+}
+
+/**
+ * List invitations for a tenant. Defaults to pending only; pass
+ * includeTerminal=true to also surface accepted/declined/revoked/
+ * expired rows for the history view. Supports `page` / `page_size`.
+ * Backend: GET /api/v1/tenants/:id/invitations (Viewer+).
+ */
+export async function listTenantInvitations(
+ tenantId: number,
+ options: ListTenantInvitationsParams = {},
+): Promise<ListInvitationsResponse> {
+ const qs = buildTenantInvitationsQuery(options)
+ return (await get(
+ `/api/v1/tenants/${tenantId}/invitations${qs}`,
+ )) as unknown as ListInvitationsResponse
+}
+
+/**
+ * Send a new invitation. The invitee will see it in /me/invitations
+ * and must accept before they actually become a member.
+ * Backend: POST /api/v1/tenants/:id/invitations (Owner+).
+ *
+ * 404 when the email is not a registered user (ask them to register).
+ * 409 when an existing pending invitation already covers this pair, or
+ * when the invitee is already an active member.
+ */
+export async function createInvitation(
+ tenantId: number,
+ body: CreateInvitationRequest,
+): Promise<CreateInvitationResponse> {
+ return (await post(
+ `/api/v1/tenants/${tenantId}/invitations`,
+ body,
+ )) as unknown as CreateInvitationResponse
+}
+
+/**
+ * Revoke a still-pending invitation. Already-finalised rows return
+ * 409; rows from another tenant render as 404 to avoid existence
+ * leaks across tenants.
+ * Backend: DELETE /api/v1/tenants/:id/invitations/:inv_id (Owner+).
+ */
+export async function revokeInvitation(
+ tenantId: number,
+ invId: number,
+): Promise<SimpleResponse> {
+ return (await del(
+ `/api/v1/tenants/${tenantId}/invitations/${invId}`,
+ )) as unknown as SimpleResponse
+}
+
+/**
+ * List MY invitations. Defaults to pending only — the inbox page
+ * filters terminal rows by default; pass includeTerminal=true for a
+ * history view if/when the UI grows one.
+ * Backend: GET /api/v1/me/invitations (authenticated).
+ */
+export async function listMyInvitations(
+ options: { includeTerminal?: boolean } = {},
+): Promise<ListInvitationsResponse> {
+ const qs = options.includeTerminal ? '?include_terminal=true' : ''
+ return (await get(`/api/v1/me/invitations${qs}`)) as unknown as ListInvitationsResponse
+}
+
+/**
+ * Lightweight pending-count endpoint used by the avatar-row badge
+ * poller. Separate from the list endpoint so polling doesn't transfer
+ * the full payload every cycle.
+ * Backend: GET /api/v1/me/invitations/pending-count (authenticated).
+ */
+export async function getMyPendingInvitationCount(): Promise<PendingCountResponse> {
+ return (await get(
+ `/api/v1/me/invitations/pending-count`,
+ )) as unknown as PendingCountResponse
+}
+
+/**
+ * Accept one of MY pending invitations. On success the backend also
+ * creates the tenant_members row in the same flow; the caller should
+ * then refresh memberships in the auth store.
+ * Backend: POST /api/v1/me/invitations/:inv_id/accept (authenticated).
+ */
+export async function acceptInvitation(invId: number): Promise<AcceptInvitationResponse> {
+ return (await post(
+ `/api/v1/me/invitations/${invId}/accept`,
+ )) as unknown as AcceptInvitationResponse
+}
+
+/**
+ * Decline one of MY pending invitations.
+ * Backend: POST /api/v1/me/invitations/:inv_id/decline (authenticated).
+ */
+export async function declineInvitation(invId: number): Promise<SimpleResponse> {
+ return (await post(
+ `/api/v1/me/invitations/${invId}/decline`,
+ )) as unknown as SimpleResponse
+}
diff --git a/frontend/src/api/tenant/members.ts b/frontend/src/api/tenant/members.ts
index b48e41b3c..f7b9df866 100644
--- a/frontend/src/api/tenant/members.ts
+++ b/frontend/src/api/tenant/members.ts
@@ -24,10 +24,30 @@ export interface ListMembersResponse {
data?: {
members: TenantMember[]
total: number
+ page?: number
+ page_size?: number
}
message?: string
}
+export interface ListMembersParams {
+ page?: number
+ page_size?: number
+ /** 按邮箱/用户名筛选(服务端模糊匹配) */
+ q?: string
+}
+
+function buildMembersQuery(params: ListMembersParams | undefined): string {
+ if (!params) return ''
+ const u = new URLSearchParams()
+ if (params.page != null && params.page > 0) u.set('page', String(params.page))
+ if (params.page_size != null && params.page_size > 0) u.set('page_size', String(params.page_size))
+ const q = params.q?.trim()
+ if (q) u.set('q', q)
+ const qs = u.toString()
+ return qs ? `?${qs}` : ''
+}
+
export interface AddMemberRequest {
email: string
role: TenantRole
@@ -45,11 +65,39 @@ export interface SimpleResponse {
}
/**
- * List all active members of the given tenant.
- * Backend: GET /api/v1/tenants/:id/members (Viewer+).
+ * 分页列出租户成员。
+ * Backend: GET /api/v1/tenants/:id/members (Viewer+)。查询参数:`q`、`page`、`page_size`。
+ */
+export async function listMembers(
+ tenantId: number,
+ params: ListMembersParams = {},
+): Promise<ListMembersResponse> {
+ const qs = buildMembersQuery(params)
+ return (await get(
+ `/api/v1/tenants/${tenantId}/members${qs}`,
+ )) as unknown as ListMembersResponse
+}
+
+/**
+ * 遍历分页拉取租户的全部成员(每页最大 100,最多 500 页兜底)。
+ * 用于「退出空间」等对全量成员的轻量校验;普通表格请直接使用 {@link listMembers} 分页接口。
*/
-export async function listMembers(tenantId: number): Promise<ListMembersResponse> {
- return (await get(`/api/v1/tenants/${tenantId}/members`)) as unknown as ListMembersResponse
+export async function fetchAllTenantMembers(tenantId: number): Promise<TenantMember[]> {
+ const pageSize = 100
+ let page = 1
+ const out: TenantMember[] = []
+ let total = Number.POSITIVE_INFINITY
+ for (let guard = 0; guard < 500 && out.length < total; guard++) {
+ const resp = await listMembers(tenantId, { page, page_size: pageSize })
+ if (!resp.success || !resp.data) break
+ total = resp.data.total
+ const batch = resp.data.members || []
+ if (batch.length === 0 && page >= 2) break
+ out.push(...batch)
+ if (batch.length < pageSize) break
+ page++
+ }
+ return out
}
/**
diff --git a/frontend/src/components/MyInvitationsDialog.vue b/frontend/src/components/MyInvitationsDialog.vue
new file mode 100644
index 000000000..fe217a7f0
--- /dev/null
+++ b/frontend/src/components/MyInvitationsDialog.vue
@@ -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>
diff --git a/frontend/src/components/TenantSelector.vue b/frontend/src/components/TenantSelector.vue
index cb3d37748..92b4941f2 100644
--- a/frontend/src/components/TenantSelector.vue
+++ b/frontend/src/components/TenantSelector.vue
@@ -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()
diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue
index a22860a9f..c66715476 100644
--- a/frontend/src/components/UserMenu.vue
+++ b/frontend/src/components/UserMenu.vue
@@ -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%;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 35350b624..39319ebe4 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -4398,6 +4398,8 @@ export default {
title: 'Members',
sectionDescription: 'Invite teammates to the tenant and manage their roles. Only Owner can add or remove members.',
totalCount: '{n} members',
+ listTitle: 'Workspace members',
+ filterMatched: '{n} matched',
loading: 'Loading members…',
retry: 'Retry',
empty: 'No members yet. Invite a teammate to get started.',
@@ -4494,6 +4496,11 @@ export default {
'rbac.member_role_changed': 'Role changed',
'rbac.member_left': 'Member left',
'rbac.access_denied': 'Access denied',
+ 'rbac.invitation_sent': 'Invitation sent',
+ 'rbac.invitation_accepted': 'Invitation accepted',
+ 'rbac.invitation_declined': 'Invitation declined',
+ 'rbac.invitation_revoked': 'Invitation revoked',
+ 'rbac.invitation_expired': 'Invitation expired',
},
outcome: {
success: 'Success',
@@ -4501,4 +4508,65 @@ export default {
},
},
},
+ tenantInvitation: {
+ inboxTooltip: 'View pending invitations',
+ pendingSectionTitle: 'Pending invitations',
+ pendingSectionCount: '{n}',
+ pendingSectionDesc:
+ 'Awaiting the invitee to accept in their inbox. Auto-expires after {days} days.',
+ pendingEmpty: 'No pending invitations.',
+ inviteSubmit: 'Send invitation',
+ inviteSuccess: 'Invitation sent. Waiting for the invitee to accept.',
+ confirmInviteTitle: 'Send invitation?',
+ confirmInviteBody:
+ 'Send an invitation to {email} (role: {role}). They will join the tenant only after accepting.',
+ confirmSend: 'Send',
+ revoke: {
+ button: 'Revoke',
+ confirmTitle: 'Revoke invitation?',
+ confirmBody:
+ "After revoke, {email} can no longer accept this invitation. You can send a new one if needed.",
+ confirm: 'Revoke',
+ success: 'Invitation revoked.',
+ },
+ columns: {
+ invitee: 'Invitee',
+ role: 'Role',
+ inviter: 'Inviter',
+ expiresAt: 'Expires',
+ status: 'Status',
+ operations: 'Actions',
+ },
+ status: {
+ pending: 'Pending',
+ accepted: 'Accepted',
+ declined: 'Declined',
+ revoked: 'Revoked',
+ expired: 'Expired',
+ },
+ myInbox: {
+ title: 'My invitations',
+ description:
+ 'Invitations from other tenants. Accept to join with the assigned role.',
+ empty: 'No pending invitations.',
+ acceptButton: 'Accept',
+ declineButton: 'Decline',
+ acceptSuccess: 'Joined "{tenant}".',
+ declineSuccess: 'Invitation declined.',
+ from: 'From',
+ tenantLabel: 'Tenant',
+ expiresIn: 'Expires: {date}',
+ messageLabel: 'Message',
+ gotoLink: 'Open inbox',
+ },
+ errors: {
+ pendingExists: 'A pending invitation for this user already exists.',
+ alreadyMember: 'This user is already an active member of the tenant.',
+ notPending: 'The invitation is no longer pending.',
+ expired: 'The invitation has expired.',
+ forbidden: 'Only the invitee can accept or decline this invitation.',
+ notFound: 'Invitation not found or already withdrawn.',
+ generic: 'Something went wrong. Please try again.',
+ },
+ },
}
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index f9fca319b..798153d25 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4458,6 +4458,8 @@ export default {
title: "멤버 관리",
sectionDescription: "테넌트에 동료를 초대하고 역할을 관리합니다. 소유자만 멤버를 추가하거나 제거할 수 있습니다.",
totalCount: "총 {n}명",
+ listTitle: "워크스페이스 멤버",
+ filterMatched: "{n}명 일치",
loading: "멤버를 불러오는 중…",
retry: "다시 시도",
empty: "아직 멤버가 없습니다. 동료를 초대해 시작하세요.",
@@ -4554,6 +4556,11 @@ export default {
"rbac.member_role_changed": "역할 변경",
"rbac.member_left": "멤버 탈퇴",
"rbac.access_denied": "접근 거부",
+ "rbac.invitation_sent": "초대 전송",
+ "rbac.invitation_accepted": "초대 수락",
+ "rbac.invitation_declined": "초대 거절",
+ "rbac.invitation_revoked": "초대 취소",
+ "rbac.invitation_expired": "초대 만료",
},
outcome: {
success: "성공",
@@ -4561,4 +4568,61 @@ export default {
},
},
},
+ tenantInvitation: {
+ inboxTooltip: "대기 중인 초대 보기",
+ pendingSectionTitle: "대기 중인 초대",
+ pendingSectionCount: "{n}",
+ pendingSectionDesc: "수신자가 수락해야 멤버로 추가됩니다. {days}일 후 자동 만료.",
+ pendingEmpty: "대기 중인 초대가 없습니다.",
+ inviteSubmit: "초대 보내기",
+ inviteSuccess: "초대가 전송되었습니다.",
+ confirmInviteTitle: "초대를 보내시겠습니까?",
+ confirmInviteBody: "{email}에게 초대를 보냅니다(역할: {role}). 수락 후 멤버가 됩니다.",
+ confirmSend: "보내기",
+ revoke: {
+ button: "취소",
+ confirmTitle: "초대를 취소하시겠습니까?",
+ confirmBody: "취소 후 {email}은 이 초대를 수락할 수 없습니다.",
+ confirm: "취소",
+ success: "초대가 취소되었습니다.",
+ },
+ columns: {
+ invitee: "초대 대상",
+ role: "역할",
+ inviter: "초대자",
+ expiresAt: "만료",
+ status: "상태",
+ operations: "작업",
+ },
+ status: {
+ pending: "대기 중",
+ accepted: "수락됨",
+ declined: "거절됨",
+ revoked: "취소됨",
+ expired: "만료됨",
+ },
+ myInbox: {
+ title: "내 초대",
+ description: "다른 워크스페이스의 초대 목록입니다.",
+ empty: "대기 중인 초대가 없습니다.",
+ acceptButton: "수락",
+ declineButton: "거절",
+ acceptSuccess: '"{tenant}"에 참여했습니다.',
+ declineSuccess: "초대를 거절했습니다.",
+ from: "초대자",
+ tenantLabel: "워크스페이스",
+ expiresIn: "만료: {date}",
+ messageLabel: "메시지",
+ gotoLink: "받은편지함 열기",
+ },
+ errors: {
+ pendingExists: "이 사용자에 대한 대기 중인 초대가 이미 있습니다.",
+ alreadyMember: "이 사용자는 이미 멤버입니다.",
+ notPending: "초대가 더 이상 대기 상태가 아닙니다.",
+ expired: "초대가 만료되었습니다.",
+ forbidden: "초대 대상자만 수락 또는 거절할 수 있습니다.",
+ notFound: "초대를 찾을 수 없거나 이미 취소되었습니다.",
+ generic: "작업에 실패했습니다. 다시 시도해 주세요.",
+ },
+ },
};
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 0ed408ffb..695c0c2d7 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4358,6 +4358,8 @@ export default {
title: 'Участники',
sectionDescription: 'Приглашайте коллег в тенант и управляйте их ролями. Добавлять и удалять участников может только Владелец.',
totalCount: 'Участников: {n}',
+ listTitle: 'Участники пространства',
+ filterMatched: 'найдено: {n}',
loading: 'Загрузка участников…',
retry: 'Повторить',
empty: 'Участников пока нет. Пригласите коллегу, чтобы начать.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index e3cca744f..e19fa4a17 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4390,6 +4390,8 @@ export default {
title: "成员管理",
sectionDescription: "邀请伙伴加入当前空间并分配角色。只有 Owner 可以新增或移除成员。",
totalCount: "共 {n} 位成员",
+ listTitle: "空间成员",
+ filterMatched: "筛选出 {n} 位",
loading: "正在加载成员…",
retry: "重试",
empty: "尚未邀请任何成员。点击右上角邀请伙伴加入。",
@@ -4486,6 +4488,11 @@ export default {
"rbac.member_role_changed": "角色变更",
"rbac.member_left": "成员退出",
"rbac.access_denied": "访问被拒",
+ "rbac.invitation_sent": "发出邀请",
+ "rbac.invitation_accepted": "接受邀请",
+ "rbac.invitation_declined": "拒绝邀请",
+ "rbac.invitation_revoked": "撤销邀请",
+ "rbac.invitation_expired": "邀请过期",
},
outcome: {
success: "成功",
@@ -4493,4 +4500,64 @@ export default {
},
},
},
+ tenantInvitation: {
+ inboxTooltip: "查看待接受的邀请",
+ pendingSectionTitle: "待接受的邀请",
+ pendingSectionCount: "{n} 条",
+ pendingSectionDesc:
+ "发出后等待对方在站内确认。{days} 天未响应将自动过期。",
+ pendingEmpty: "暂无待接受的邀请。",
+ inviteSubmit: "发送邀请",
+ inviteSuccess: "邀请已发出,等待对方接受。",
+ confirmInviteTitle: "确认发送邀请?",
+ confirmInviteBody:
+ "将向 {email} 发出加入邀请(角色:{role})。TA 在站内接受后才会成为成员。",
+ confirmSend: "发送",
+ revoke: {
+ button: "撤销",
+ confirmTitle: "确认撤销邀请?",
+ confirmBody:
+ "撤销后,{email} 将无法再接受此邀请;如需再邀请请重新发出。",
+ confirm: "撤销",
+ success: "邀请已撤销。",
+ },
+ columns: {
+ invitee: "被邀请人",
+ role: "角色",
+ inviter: "邀请人",
+ expiresAt: "到期时间",
+ status: "状态",
+ operations: "操作",
+ },
+ status: {
+ pending: "待接受",
+ accepted: "已接受",
+ declined: "已拒绝",
+ revoked: "已撤销",
+ expired: "已过期",
+ },
+ myInbox: {
+ title: "我的邀请",
+ description: "其他空间发给您的加入邀请。接受后您将以对应角色加入对方空间。",
+ empty: "没有待处理的邀请。",
+ acceptButton: "接受",
+ declineButton: "拒绝",
+ acceptSuccess: '已加入 "{tenant}"。',
+ declineSuccess: "已拒绝邀请。",
+ from: "邀请人",
+ tenantLabel: "空间",
+ expiresIn: "到期:{date}",
+ messageLabel: "留言",
+ gotoLink: "进入收件箱",
+ },
+ errors: {
+ pendingExists: "已经向该用户发出过一条待接受的邀请。",
+ alreadyMember: "该用户已是当前空间的成员。",
+ notPending: "邀请已不在待处理状态。",
+ expired: "邀请已过期。",
+ forbidden: "只有被邀请人本人可以接受或拒绝该邀请。",
+ notFound: "邀请不存在或已被撤销。",
+ generic: "操作失败,请稍后重试。",
+ },
+ },
};
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index e0e027ed5..9f3d9fd9c 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -34,6 +34,13 @@ export const useAuthStore = defineStore('auth', () => {
// so PR 3 can render a tenant-switcher UI without a store migration.
const memberships = ref<Array<{ tenant_id: number; tenant_name?: string; role: string }>>([])
const isLiteMode = ref(false)
+ // pendingInvitationCount is the number of pending tenant invitations
+ // addressed to the current user. Renders as a badge next to the
+ // avatar; updated by fetchPendingInvitationCount, which runs after
+ // login, after tenant switch, and on a polling interval. Polling
+ // (vs SSE) is fine — the count is checked rarely and a 1-2 minute
+ // staleness window is acceptable for an inbox indicator.
+ const pendingInvitationCount = ref<number>(0)
// 计算属性
const isLoggedIn = computed(() => {
@@ -240,6 +247,85 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.setItem('weknora_memberships', JSON.stringify(memberships.value))
}
+ // setPendingInvitationCount is the explicit setter used by the
+ // polling composable below. Keeping the mutation behind a setter
+ // matches the pattern of every other piece of auth state and lets
+ // future devtools / strict-mode checks intercept the write.
+ const setPendingInvitationCount = (n: number) => {
+ pendingInvitationCount.value = Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0
+ }
+
+ // fetchPendingInvitationCount hits the dedicated /me/invitations/
+ // pending-count endpoint and updates the store. Errors are
+ // swallowed — the badge degrades to its last-known value instead
+ // of nagging the user with a toast. The caller can choose to fire
+ // and forget (login flow) or await (manual refresh button).
+ const fetchPendingInvitationCount = async () => {
+ // Import lazily to avoid circular module ordering between auth
+ // store, axios interceptor, and i18n bootstrapping. The store is
+ // imported by very early modules in main.ts; a top-level api
+ // import would tighten that graph unnecessarily.
+ try {
+ const { getMyPendingInvitationCount } = await import('@/api/tenant/invitations')
+ const resp = await getMyPendingInvitationCount()
+ if (resp.success && resp.data) {
+ setPendingInvitationCount(resp.data.pending_count)
+ }
+ } catch {
+ // best-effort; keep last known value
+ }
+ }
+
+ // Reconcile user / home tenant / memberships with GET /api/v1/auth/me.
+ // Login only populated memberships once; SPA navigations skip
+ // hydrateSessionFromToken when isLoggedIn is already true — so inviting
+ // flows or revokes would leave the sidebar switcher stale until reload.
+ const refreshFromAuthMe = async (): Promise<boolean> => {
+ try {
+ const { getCurrentUser } = await import('@/api/auth')
+ const response = await getCurrentUser()
+ const u = response.data?.user
+ if (!response.success || !u) return false
+
+ setUser({
+ id: u.id || '',
+ username: u.username || '',
+ email: u.email || '',
+ avatar: u.avatar,
+ tenant_id: String(u.tenant_id || response.data?.tenant?.id || ''),
+ can_access_all_tenants: u.can_access_all_tenants || false,
+ created_at: u.created_at || new Date().toISOString(),
+ updated_at: u.updated_at || new Date().toISOString(),
+ })
+
+ const tenantSnapshot = response.data?.tenant
+ if (tenantSnapshot) {
+ setTenant({
+ id: String(tenantSnapshot.id) || '',
+ name: tenantSnapshot.name || '',
+ api_key: tenantSnapshot.api_key || '',
+ owner_id: tenantSnapshot.owner_id || u.id || '',
+ description: tenantSnapshot.description,
+ status: tenantSnapshot.status,
+ business: tenantSnapshot.business,
+ storage_quota: tenantSnapshot.storage_quota,
+ storage_used: tenantSnapshot.storage_used,
+ created_at: tenantSnapshot.created_at || new Date().toISOString(),
+ updated_at: tenantSnapshot.updated_at || new Date().toISOString(),
+ })
+ }
+
+ const list = response.data?.memberships
+ if (Array.isArray(list)) {
+ setMemberships(list)
+ }
+
+ return true
+ } catch {
+ return false
+ }
+ }
+
const getSelectedTenant = () => {
return selectedTenantId.value
}
@@ -265,6 +351,7 @@ export const useAuthStore = defineStore('auth', () => {
selectedTenantName.value = null
allTenants.value = []
memberships.value = []
+ pendingInvitationCount.value = 0
// 清空localStorage
localStorage.removeItem('weknora_user')
@@ -381,6 +468,7 @@ export const useAuthStore = defineStore('auth', () => {
selectedTenantName,
allTenants,
memberships,
+ pendingInvitationCount,
// 计算属性
isLoggedIn,
@@ -404,6 +492,9 @@ export const useAuthStore = defineStore('auth', () => {
setSelectedTenant,
setAllTenants,
setMemberships,
+ setPendingInvitationCount,
+ fetchPendingInvitationCount,
+ refreshFromAuthMe,
getSelectedTenant,
setLiteMode,
logout,
diff --git a/frontend/src/views/settings/TenantInfo.vue b/frontend/src/views/settings/TenantInfo.vue
index 979ff0663..42a0400dd 100644
--- a/frontend/src/views/settings/TenantInfo.vue
+++ b/frontend/src/views/settings/TenantInfo.vue
@@ -178,7 +178,7 @@ import { getCurrentUser, type TenantInfo } from '@/api/auth'
import { updateTenant as updateTenantApi } from '@/api/tenant'
import {
leaveTenant,
- listMembers,
+ fetchAllTenantMembers,
type TenantMember,
type TenantRole,
} from '@/api/tenant/members'
@@ -245,10 +245,7 @@ async function evaluateLeaveGate(): Promise<void> {
leaveGateLoading.value = true
try {
- const resp = await listMembers(infoId)
- if (resp.success && resp.data?.members) {
- leaveMembersSnap.value = resp.data.members
- }
+ leaveMembersSnap.value = await fetchAllTenantMembers(infoId)
} finally {
leaveGateLoading.value = false
leaveGateReady.value = true
diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue
index 4c16b047a..c264e174d 100644
--- a/frontend/src/views/settings/TenantMembers.vue
+++ b/frontend/src/views/settings/TenantMembers.vue
@@ -1,99 +1,235 @@
<template>
<div class="tenant-members">
+ <!-- Section header. The (i) permission speed-look popover lives
+ next to the title so it reads as meta-info about *this
+ section*. The audit-log entry sits on the right of the header
+ row — secondary navigation that opens the audit drawer; gated
+ to Admin+ so non-managers don't see a button they can't use. -->
<div class="section-header">
- <h2>{{ $t('tenantMember.title') }}</h2>
- <p class="section-description">{{ $t('tenantMember.sectionDescription') }}</p>
- </div>
-
- <!-- Two-tab layout. The Members tab is the original UI verbatim; the
- Audit log tab is gated to Admin+ because it can leak denial
- histories and member-management activity that ordinary members
- shouldn't see. -->
- <t-tabs v-model="activeTab" placement="top" class="tenant-members-tabs">
- <t-tab-panel value="members" :label="$t('tenantMember.tabs.members')">
- <div class="members-tab-layout">
- <!-- Toolbar:统计一行、检索一行,避免单行挤压力过大 -->
- <div class="members-toolbar">
- <div class="toolbar-meta">
- <span class="toolbar-count">{{ $t('tenantMember.totalCount', { n: members.length }) }}</span>
- <span class="toolbar-meta-sep" aria-hidden="true" />
- <t-popup placement="bottom-start" trigger="hover" overlay-class-name="permissions-popup-overlay"
- :overlay-inner-style="permissionsPopupInnerStyle">
- <button type="button" class="permissions-trigger-btn" :aria-label="$t('tenantMember.permissions.title')"
- :title="$t('tenantMember.permissions.iconHint')">
- <t-icon name="info-circle" size="18px" />
- </button>
- <template #content>
- <div class="permissions-compact permissions-compact--popover">
- <div class="permissions-compact-header">
- <span class="permissions-compact-title">{{ $t('tenantMember.permissions.title') }}</span>
- <span class="permissions-compact-desc">{{ $t('tenantMember.permissions.desc') }}</span>
+ <div class="section-header-row">
+ <div class="section-header-titlewrap">
+ <h2>{{ $t('tenantMember.title') }}</h2>
+ <t-popup placement="bottom-start" trigger="hover" overlay-class-name="permissions-popup-overlay"
+ :overlay-inner-style="permissionsPopupInnerStyle">
+ <button type="button" class="permissions-trigger-btn" :aria-label="$t('tenantMember.permissions.title')"
+ :title="$t('tenantMember.permissions.iconHint')">
+ <t-icon name="info-circle" size="16px" />
+ </button>
+ <template #content>
+ <div class="permissions-compact permissions-compact--popover">
+ <div class="permissions-compact-header">
+ <span class="permissions-compact-title">{{ $t('tenantMember.permissions.title') }}</span>
+ <span class="permissions-compact-desc">{{ $t('tenantMember.permissions.desc') }}</span>
+ </div>
+ <div class="permissions-compact-grid">
+ <div v-for="r in roleMatrixOrder" :key="r"
+ :class="['perm-role-block', r, { 'is-me': currentRole === r }]">
+ <div class="perm-role-tag">
+ <t-icon :name="roleMatrixIcon(r)" size="12px" />
+ <span>{{ $t('tenantMember.role.' + r) }}</span>
+ <span v-if="currentRole === r" class="me-badge">{{ $t('common.me') }}</span>
</div>
- <div class="permissions-compact-grid">
- <div v-for="r in roleMatrixOrder" :key="r"
- :class="['perm-role-block', r, { 'is-me': currentRole === r }]">
- <div class="perm-role-tag">
- <t-icon :name="roleMatrixIcon(r)" size="12px" />
- <span>{{ $t('tenantMember.role.' + r) }}</span>
- <span v-if="currentRole === r" class="me-badge">{{ $t('common.me') }}</span>
- </div>
- <div class="perm-items">
- <span v-for="(perm, i) in roleMatrix[r]" :key="i"
- :class="['perm-item', perm.has ? 'has' : 'no']">
- <t-icon :name="perm.has ? 'check' : 'close'" size="12px" />
- {{ $t('tenantMember.permissions.' + perm.key) }}
- </span>
- </div>
- </div>
+ <div class="perm-items">
+ <span v-for="(perm, i) in roleMatrix[r]" :key="i" :class="['perm-item', perm.has ? 'has' : 'no']">
+ <t-icon :name="perm.has ? 'check' : 'close'" size="12px" />
+ {{ $t('tenantMember.permissions.' + perm.key) }}
+ </span>
</div>
</div>
- </template>
- </t-popup>
- </div>
- <div class="toolbar-controls">
- <div class="toolbar-actions-bar">
- <div class="toolbar-search">
- <t-input v-model="searchQuery" size="medium" :placeholder="$t('tenantMember.searchPlaceholder')"
- clearable class="toolbar-search-input">
- <template #prefix-icon><t-icon name="search" /></template>
- </t-input>
- </div>
- <div class="toolbar-btn-group">
- <t-button v-if="canManage" theme="primary" size="medium" @click="openAddDialog">
- {{ $t('tenantMember.add.button') }}
- </t-button>
</div>
</div>
- </div>
- </div>
+ </template>
+ </t-popup>
+ <!-- Audit log entry sits inline with the title: title (i)
+ [审计日志]. Keeping all section-level affordances on the
+ left edge avoids the "lonely right-aligned button"
+ pattern in narrow settings panels. -->
+ <t-button v-if="canViewAudit" variant="text" size="small" class="header-audit-btn" @click="openAuditDrawer">
+ <template #icon><t-icon name="history" /></template>
+ {{ $t('tenantMember.audit.tabLabel') }}
+ </t-button>
+ </div>
+ </div>
+ <p class="section-description">{{ $t('tenantMember.sectionDescription') }}</p>
+ </div>
- <!-- Loading -->
- <div v-if="loading" class="loading-inline">
- <t-loading size="small" />
- <span>{{ $t('tenantMember.loading') }}</span>
+ <div class="members-tab-layout">
+ <!-- Toolbar 已被并入「空间成员」列表头:搜索框紧贴列表头右
+ 侧,邀请按钮再往右一个图标位,所有「针对这张列表」的控
+ 件聚到同一行,独立 toolbar 不复存在。 -->
+
+ <!-- Pending invitations. Shown only to managers because the
+ viewer/contributor roles don't have an action surface
+ here. Even when empty we still render the header so
+ operators get a stable "is there anything pending?"
+ affordance after they hit "Send invitation". -->
+ <div v-if="canManage" class="pending-invitations-section">
+ <div class="pending-invitations-header">
+ <div class="pending-invitations-titlewrap">
+ <span class="pending-invitations-title">
+ {{ $t('tenantInvitation.pendingSectionTitle') }}
+ </span>
+ <!-- Same count-badge style as the «空间成员» list header
+ so the two list titles read at parity. -->
+ <span class="members-list-count-badge">{{ invitationsTotal }}</span>
</div>
-
- <!-- Error -->
- <div v-else-if="error" class="error-inline">
- <t-alert theme="error" :message="error">
- <template #operation>
- <t-button size="small" @click="loadMembers">{{ $t('tenantMember.retry') }}</t-button>
+ <span class="pending-invitations-desc">
+ {{ $t('tenantInvitation.pendingSectionDesc', { days: INVITATION_TTL_DAYS }) }}
+ </span>
+ </div>
+ <div v-if="invitationsLoading" class="loading-inline">
+ <t-loading size="small" />
+ <span>{{ $t('tenantMember.loading') }}</span>
+ </div>
+ <div v-else-if="invitationsError" class="error-inline">
+ <t-alert theme="error" :message="invitationsError">
+ <template #operation>
+ <t-button size="small" @click="loadInvitations">{{ $t('tenantMember.retry') }}</t-button>
+ </template>
+ </t-alert>
+ </div>
+ <div v-else-if="invitationsTotal === 0" class="pending-invitations-empty">
+ {{ $t('tenantInvitation.pendingEmpty') }}
+ </div>
+ <div v-else class="data-table-shell data-table-shell--with-footer pending-invitations-table">
+ <div class="data-table-shell__scroll">
+ <t-table row-key="id" :data="invitations" :columns="invitationColumns" size="medium" hover>
+ <template #invitee="{ row }">
+ <div class="member-cell">
+ <span class="member-name">{{ inviteePrimary(row) }}</span>
+ <span v-if="row.invitee_email && row.invitee_name" class="member-email">{{ row.invitee_email
+ }}</span>
+ </div>
+ </template>
+ <template #role="{ row }">
+ <t-tag :theme="roleTagTheme(row.role)" size="small">
+ {{ $t('tenantMember.role.' + row.role) }}
+ </t-tag>
</template>
- </t-alert>
+ <template #inviter="{ row }">
+ <span>{{ inviterPrimary(row) }}</span>
+ </template>
+ <template #expires_at="{ row }">{{ formatDate(row.expires_at) }}</template>
+ <template #status="{ row }">
+ <t-tag :theme="invitationStatusTheme(row.status)" size="small">
+ {{ $t('tenantInvitation.status.' + row.status) }}
+ </t-tag>
+ </template>
+ <template #actions="{ row }">
+ <!-- Inline popconfirm anchored to the revoke button.
+ Avoids spawning a top-level modal for a simple
+ yes/no decision; the popover stays inside the
+ table cell so the user keeps spatial context. -->
+ <t-popconfirm v-if="row.status === 'pending'" theme="warning" :content="$t('tenantInvitation.revoke.confirmBody', {
+ email: row.invitee_email || row.invitee_user_id,
+ })" :confirm-btn="{ content: $t('tenantInvitation.revoke.confirm'), theme: 'danger' }"
+ :cancel-btn="$t('common.cancel')" placement="left" @confirm="doRevokeInvitation(row)">
+ <t-button theme="danger" variant="text" size="small">
+ {{ $t('tenantInvitation.revoke.button') }}
+ </t-button>
+ </t-popconfirm>
+ </template>
+ </t-table>
</div>
-
- <!-- Empty state when there are no members at all OR the search query
- filters everything out. -->
- <div v-else-if="filteredMembers.length === 0" class="empty-state">
- <t-empty :description="searchQuery
- ? $t('tenantMember.emptySearch', { q: searchQuery })
- : $t('tenantMember.empty')
- " />
+ <div v-if="invitationsTotal > 0" class="data-table-shell__pager">
+ <t-pagination v-model="invitationsPage" v-model:page-size="invitationsPageSize" :total="invitationsTotal"
+ size="small" show-jumper show-page-number show-page-size
+ :page-size-options="INVITATIONS_PAGE_SIZE_OPTIONS" @change="onInvitationsPageChange" />
</div>
-
- <!-- Member table -->
- <div v-else class="data-table-shell">
- <t-table row-key="user_id" :data="filteredMembers" :columns="columns" size="medium" hover stripe>
+ </div>
+ </div>
+
+ <!-- Loading -->
+ <div v-if="loading" class="loading-inline">
+ <t-loading size="small" />
+ <span>{{ $t('tenantMember.loading') }}</span>
+ </div>
+
+ <!-- Error -->
+ <div v-else-if="error" class="error-inline">
+ <t-alert theme="error" :message="error">
+ <template #operation>
+ <t-button size="small" @click="loadMembers">{{ $t('tenantMember.retry') }}</t-button>
+ </template>
+ </t-alert>
+ </div>
+
+ <!-- 无成员或当前筛选条件下无命中 -->
+ <div v-else-if="membersTotal === 0" class="empty-state">
+ <t-empty :description="searchQuery.trim()
+ ? $t('tenantMember.emptySearch', { q: searchQuery })
+ : $t('tenantMember.empty')
+ " />
+ </div>
+
+ <!-- Member table. The list is preceded by a small section title
+ («成员 N +») that mirrors the "Pending invitations" header
+ above it. The trailing «+» icon button replaces the toolbar
+ "Invite member" CTA — the action belongs next to the list it
+ mutates, not in a separate band. -->
+ <div v-else class="members-list-wrap">
+ <div class="members-list-header">
+ <div class="members-list-titlewrap">
+ <span class="members-list-title">{{ $t('tenantMember.listTitle') }}</span>
+ <span class="members-list-count-badge">{{ membersTotal }}</span>
+ </div>
+ <div class="members-list-actions">
+ <div class="members-list-search">
+ <t-input v-model="searchQuery" size="small" :placeholder="$t('tenantMember.searchPlaceholder')" clearable>
+ <template #prefix-icon><t-icon name="search" /></template>
+ </t-input>
+ </div>
+ <t-popup v-if="canManage" v-model="invitePopupVisible" trigger="click" placement="bottom-end"
+ destroy-on-close overlay-class-name="member-invite-popup-overlay">
+ <t-button theme="primary" variant="outline" shape="square" size="small" class="members-list-add-btn"
+ :title="$t('tenantMember.add.button')" :aria-label="$t('tenantMember.add.button')">
+ <template #icon><t-icon name="user-add" /></template>
+ </t-button>
+ <template #content>
+ <div class="member-invite-popup-inner" @click.stop>
+ <div class="member-invite-popup-title">
+ {{
+ addDialogStep === 'form'
+ ? $t('tenantMember.add.dialogTitle')
+ : $t('tenantInvitation.confirmInviteTitle')
+ }}
+ </div>
+ <t-form v-if="addDialogStep === 'form'" ref="addFormRef" :data="addForm" :rules="addFormRules"
+ :label-width="80" class="member-invite-form">
+ <t-form-item :label="$t('tenantMember.add.emailLabel')" name="email">
+ <t-input v-model="addForm.email" :placeholder="$t('tenantMember.add.emailPlaceholder')"
+ clearable />
+ </t-form-item>
+ <t-form-item :label="$t('tenantMember.add.roleLabel')" name="role">
+ <t-select v-model="addForm.role" :options="roleOptions" :popup-props="roleSelectPopupProps" />
+ </t-form-item>
+ </t-form>
+ <div v-else class="invite-confirm-body">
+ {{ $t('tenantInvitation.confirmInviteBody', {
+ email: addConfirmEmail,
+ role: addConfirmRoleLabel,
+ }) }}
+ </div>
+ <div class="invite-popup-footer">
+ <t-button v-if="addDialogStep === 'form'" variant="outline" :disabled="adding"
+ @click="invitePopupVisible = false">
+ {{ $t('common.cancel') }}
+ </t-button>
+ <t-button v-else variant="outline" :disabled="adding" @click="goBackToForm">
+ {{ $t('common.back') }}
+ </t-button>
+ <t-button theme="primary" :loading="adding" @click="submitAdd">
+ {{ dialogConfirmLabel }}
+ </t-button>
+ </div>
+ </div>
+ </template>
+ </t-popup>
+ </div>
+ </div>
+ <div class="data-table-shell data-table-shell--with-footer">
+ <div class="data-table-shell__scroll">
+ <t-table row-key="user_id" :data="members" :columns="columns" size="medium" hover stripe>
<template #member="{ row }">
<div class="member-cell">
<span class="member-name">{{ memberPrimary(row) }}</span>
@@ -103,7 +239,7 @@
<template #role="{ row }">
<div class="role-cell">
<t-select v-if="canManage && row.user_id !== currentUserId" :model-value="row.role"
- class="member-role-select" :options="roleOptions" size="small"
+ class="member-role-select" :options="roleOptions" size="small" :popup-props="roleSelectPopupProps"
@change="(val: string) => onRoleChange(row, val)" />
<t-tag v-else :theme="roleTagTheme(row.role)" size="small">
{{ $t('tenantMember.role.' + row.role) }}
@@ -119,118 +255,120 @@
</template>
</t-table>
</div>
+ <div v-if="membersTotal > 0" class="data-table-shell__pager">
+ <t-pagination v-model="membersPage" v-model:page-size="membersPageSize" :total="membersTotal" size="small"
+ show-jumper show-page-number show-page-size :page-size-options="MEMBERS_PAGE_SIZE_OPTIONS"
+ @change="onMembersPageChange" />
+ </div>
+ </div>
+ </div>
- <!-- Add dialog. We use @confirm rather than :on-confirm so we can
- keep the dialog open on validation failure / API error and let
- the user retry without retyping. -->
- <t-dialog v-model:visible="addDialogVisible" :header="$t('tenantMember.add.dialogTitle')"
- :confirm-btn="{ content: $t('tenantMember.add.submit'), loading: adding }"
- :cancel-btn="{ content: $t('common.cancel') }" width="480px" @confirm="submitAdd">
- <t-form ref="addFormRef" :data="addForm" :rules="addFormRules" :label-width="80">
- <t-form-item :label="$t('tenantMember.add.emailLabel')" name="email">
- <t-input v-model="addForm.email" :placeholder="$t('tenantMember.add.emailPlaceholder')" clearable />
- </t-form-item>
- <t-form-item :label="$t('tenantMember.add.roleLabel')" name="role">
- <t-select v-model="addForm.role" :options="roleOptions" />
- </t-form-item>
- </t-form>
- </t-dialog>
+ </div>
+ <!-- Audit log drawer. Only rendered for Admin+ because the backend
+ route is g.Admin()-gated; rendering it for lower roles would
+ just produce an unhelpful 403. Lazy-loaded on first open. -->
+ <t-drawer v-if="canViewAudit" v-model:visible="auditDrawerVisible" :header="$t('tenantMember.audit.tabLabel')"
+ drawer-class-name="tenant-members-audit-drawer" size="720px" :footer="false" placement="right" destroy-on-close>
+ <div class="audit-drawer-inner audit-panel audit-panel--drawer">
+ <div class="audit-header">
+ <span class="audit-desc">{{ $t('tenantMember.audit.description') }}</span>
+ <t-button theme="primary" variant="outline" shape="square" size="small" class="audit-refresh-btn"
+ :loading="auditLoading" :title="$t('tenantMember.audit.refresh')"
+ :aria-label="$t('tenantMember.audit.refresh')" @click="reloadAuditLog">
+ <template #icon><t-icon name="refresh" /></template>
+ </t-button>
</div>
- </t-tab-panel>
-
- <!-- Audit log tab. Only rendered for Admin+ because the backend
- route is g.Admin()-gated; rendering it for lower roles would
- just produce an unhelpful 403. -->
- <t-tab-panel v-if="canViewAudit" value="audit" :label="$t('tenantMember.audit.tabLabel')">
- <div class="audit-panel">
- <div class="audit-header">
- <span class="audit-desc">{{ $t('tenantMember.audit.description') }}</span>
- <t-button variant="outline" :loading="auditLoading" @click="reloadAuditLog">
- {{ $t('tenantMember.audit.refresh') }}
- </t-button>
- </div>
- <div v-if="auditError" class="error-inline">
- <t-alert theme="error" :message="auditError">
- <template #operation>
- <t-button size="small" @click="reloadAuditLog">
- {{ $t('tenantMember.retry') }}
- </t-button>
- </template>
- </t-alert>
+ <div class="audit-drawer-fill">
+ <div v-if="auditError" class="audit-drawer-branch audit-drawer-branch--error">
+ <div class="error-inline">
+ <t-alert theme="error" :message="auditError">
+ <template #operation>
+ <t-button size="small" @click="reloadAuditLog">
+ {{ $t('tenantMember.retry') }}
+ </t-button>
+ </template>
+ </t-alert>
+ </div>
</div>
- <div v-else-if="!auditLoading && auditEntries.length === 0" class="empty-state">
+ <div v-else-if="!auditLoading && auditEntries.length === 0"
+ class="audit-drawer-branch audit-drawer-branch--empty empty-state empty-state--audit">
<t-empty :description="$t('tenantMember.audit.empty')" />
</div>
- <div v-else class="data-table-shell">
- <t-table row-key="id" :data="auditEntries" :columns="auditColumns" size="medium" hover stripe>
- <template #created_at="{ row }">{{ formatDate(row.created_at) }}</template>
- <template #actor="{ row }">
- <span class="audit-actor">
- {{ row.actor_user_id ? actorDisplayName(row.actor_user_id) : $t('tenantMember.audit.systemActor') }}
- <span v-if="row.actor_role" class="audit-actor-role">
- · {{ $t('tenantMember.role.' + row.actor_role) }}
+ <div v-else class="audit-scroll-area narrow-scrollbar audit-drawer-branch" ref="auditScrollRoot">
+ <div class="data-table-shell">
+ <t-table row-key="id" :data="auditEntries" :columns="auditColumns" size="medium" hover stripe>
+ <template #created_at="{ row }">{{ formatDate(row.created_at) }}</template>
+ <template #actor="{ row }">
+ <span class="audit-actor">
+ {{ row.actor_user_id ? actorDisplayName(row.actor_user_id) :
+ $t('tenantMember.audit.systemActor') }}
+ <span v-if="row.actor_role" class="audit-actor-role">
+ · {{ $t('tenantMember.role.' + row.actor_role) }}
+ </span>
</span>
- </span>
- </template>
- <template #action="{ row }">
- <t-tag :theme="auditActionTheme(row.action)" size="small">
- {{ formatAuditAction(row.action) }}
- </t-tag>
- </template>
- <template #target="{ row }">
- <span class="audit-target">{{ formatAuditTarget(row) }}</span>
- </template>
- <template #request_path="{ row }">
- <span class="audit-path">
- <span v-if="row.request_method" class="audit-method">{{ row.request_method }}</span>
- {{ row.request_path || '-' }}
- </span>
- </template>
- <template #outcome="{ row }">
- <t-tag :theme="auditOutcomeTheme(row.outcome)" size="small">
- {{ $t('tenantMember.audit.outcome.' + row.outcome) }}
- </t-tag>
- </template>
- </t-table>
- </div>
+ </template>
+ <template #action="{ row }">
+ <t-tag :theme="auditActionTheme(row.action)" size="small">
+ {{ formatAuditAction(row.action) }}
+ </t-tag>
+ </template>
+ <template #target="{ row }">
+ <span class="audit-target">{{ formatAuditTarget(row) }}</span>
+ </template>
+ <template #request_path="{ row }">
+ <span class="audit-path">
+ <span v-if="row.request_method" class="audit-method">{{ row.request_method }}</span>
+ {{ row.request_path || '-' }}
+ </span>
+ </template>
+ <template #outcome="{ row }">
+ <t-tag :theme="auditOutcomeTheme(row.outcome)" size="small">
+ {{ $t('tenantMember.audit.outcome.' + row.outcome) }}
+ </t-tag>
+ </template>
+ </t-table>
+ </div>
+
+ <!-- 触底 sentinel:IntersectionObserver root 指向 audit-scroll-area -->
+ <div ref="auditLoadSentinelEl" class="audit-load-sentinel" aria-hidden="true" />
+
+ <div v-if="auditLoading && auditEntries.length > 0" class="audit-loading-more">
+ <t-loading size="small" />
+ <span>{{ $t('tenantMember.loading') }}</span>
+ </div>
- <!-- Footer: load-more cursor. We avoid actual infinite-scroll
- (IntersectionObserver) because the table sits inside a
- scroll container that's already deep in the settings
- panel; an explicit button keeps behaviour predictable
- under unusual layouts. -->
- <div class="audit-footer">
- <t-button v-if="auditHasMore" size="small" variant="outline" :loading="auditLoading"
- @click="loadAuditLog(false)">
- {{ $t('tenantMember.audit.loadMore') }}
- </t-button>
- <span v-else-if="auditEntries.length > 0" class="audit-end">
+ <p v-if="!auditHasMore && auditEntries.length > 0 && !auditLoading" class="audit-end-hint">
{{ $t('tenantMember.audit.end') }}
- </span>
+ </p>
</div>
</div>
- </t-tab-panel>
- </t-tabs>
+ </div>
+ </t-drawer>
</div>
</template>
<script setup lang="ts">
-import { computed, onMounted, reactive, ref, watch } from 'vue'
+import { computed, nextTick, onUnmounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import {
listMembers,
- addMember,
updateMemberRole,
removeMember,
type TenantMember,
type TenantRole,
} from '@/api/tenant/members'
+import {
+ listTenantInvitations,
+ createInvitation,
+ revokeInvitation,
+ type TenantInvitation,
+} from '@/api/tenant/invitations'
import {
listAuditLog,
type AuditLog,
@@ -238,7 +376,7 @@ import {
type AuditOutcome,
} from '@/api/tenant/audit-log'
-const { t, locale } = useI18n()
+const { t, tm, locale } = useI18n()
const authStore = useAuthStore()
/** 悬停层限制在视口内,内容由内部滚动 */
@@ -256,18 +394,57 @@ const members = ref<TenantMember[]>([])
const loading = ref(false)
const error = ref('')
const adding = ref(false)
-const addDialogVisible = ref(false)
+/** 邀请流程:锚在列表头「+」按钮旁的弹出层(非居中模态)。 */
+const invitePopupVisible = ref(false)
+// Two-step invite inside the popup: 'form' renders the email/role inputs;
+// 'confirm' swaps the body for an in-place summary; primary CTA toggles label.
+const addDialogStep = ref<'form' | 'confirm'>('form')
const addFormRef = ref<any>(null)
const searchQuery = ref('')
-
-// Tab state. Default to "members" — audit-log is the secondary view
-// even for admins, who still mostly come here to manage members.
-const activeTab = ref<'members' | 'audit'>('members')
-
-// Audit-log state. Cursor-paginated by descending id; once
-// `next_cursor` comes back as 0 we stop offering "load more". Page
-// size is 50 (server default), large enough to feel responsive while
-// keeping the table tractable on a small settings panel.
+/** 已应用到服务端筛选的检索词(相对输入框防抖) */
+const memberSearchQ = ref('')
+let memberSearchDebounceTimer: number | undefined
+
+const membersTotal = ref(0)
+const membersPage = ref(1)
+const membersPageSize = ref(20)
+
+const invitationsTotal = ref(0)
+const invitationsPage = ref(1)
+const invitationsPageSize = ref(20)
+
+/** 历次分页载荷里见过的成员展示字段,补齐审计表里不在当前页的 user id */
+const memberDisplayByUserId = reactive<Record<string, { username?: string; email?: string }>>({})
+
+// Pending invitations live alongside members but in a distinct section
+// at the top of the Members tab — they're "people we've asked to
+// join but haven't yet accepted", and conflating them with the
+// authoritative roster would mislead an Owner trying to see who
+// actually has access. The load happens on the same trigger as the
+// members fetch so the screen renders both at once.
+const invitations = ref<TenantInvitation[]>([])
+const invitationsLoading = ref(false)
+const invitationsError = ref('')
+// Invitation TTL is mirrored from the backend constant
+// (defaultInvitationTTL in tenant_invitation.go). Kept as a UI string
+// for the section description; the authoritative number comes from
+// the server's expires_at on each row.
+const INVITATION_TTL_DAYS = 7
+
+const MEMBERS_PAGE_SIZE_OPTIONS = [10, 20, 50, 100]
+const INVITATIONS_PAGE_SIZE_OPTIONS = [10, 20, 50, 100]
+
+// Audit log moved out of t-tabs into a right-side drawer; this flag
+// controls its visibility. Default closed — most operators come here
+// to manage members, not to audit. Lazy-load logic is wired through
+// openAuditDrawer() rather than a watch() on the visibility flag so a
+// re-open of the drawer doesn't re-trigger a fetch the user didn't ask
+// for (they have an explicit "refresh" button inside the drawer).
+const auditDrawerVisible = ref(false)
+
+// Audit-log state. Backend cursor-paged by descending id (`after_id`);
+// frontend appends rows when the sentinel scrolls into view. When
+// `next_cursor` is 0, `auditHasMore` becomes false and loading stops.
const auditEntries = ref<AuditLog[]>([])
const auditLoading = ref(false)
const auditError = ref('')
@@ -276,6 +453,11 @@ const auditHasMore = ref(true)
const auditLoadedOnce = ref(false)
const AUDIT_PAGE_SIZE = 50
+/** 抽屉内滚动根与触底 sentinel,用于游标分页自动加载下一页(见 attachAuditInfiniteScroll) */
+const auditScrollRoot = ref<HTMLElement | null>(null)
+const auditLoadSentinelEl = ref<HTMLElement | null>(null)
+let auditScrollObserver: IntersectionObserver | null = null
+
// Add dialog model — reset on each open. Default role is contributor:
// inviting a fresh member with viewer is too restrictive for the
// expected "let them collaborate on KBs" use case, and admin/owner
@@ -319,6 +501,12 @@ const roleOptions = computed(() => [
{ label: t('tenantMember.role.viewer'), value: 'viewer' },
])
+/** 下拉层须高于邀请浮层(3050)与组织设置全屏遮罩,否则会被压住 */
+const roleSelectPopupProps = {
+ zIndex: 6200,
+ overlayClassName: 'tenant-members-role-select-popup',
+}
+
// Static role-permissions matrix. The keys reference i18n strings under
// `tenantMember.permissions.*` so each locale can rephrase per culture.
// Keep this aligned with the design-doc §4.3 matrix and the actual
@@ -360,7 +548,7 @@ const roleMatrix: Record<TenantRole, RolePerm[]> = {
function roleMatrixIcon(role: TenantRole): string {
switch (role) {
case 'owner':
- return 'crown'
+ return 'user-vip-filled'
case 'admin':
return 'user-safety'
case 'contributor':
@@ -372,7 +560,7 @@ function roleMatrixIcon(role: TenantRole): string {
const columns = computed(() => [
{ colKey: 'member', title: t('tenantMember.columns.member'), ellipsis: true, minWidth: 160 },
- { colKey: 'role', title: t('tenantMember.columns.role'), width: 140 },
+ { colKey: 'role', title: t('tenantMember.columns.role'), width: 112 },
{ colKey: 'joined_at', title: t('tenantMember.columns.joinedAt'), width: 154 },
{ colKey: 'actions', title: t('tenantMember.columns.operations'), width: 88, align: 'right' },
])
@@ -427,34 +615,44 @@ function formatDate(s: string | undefined): string {
}
}
-// Client-side filter by username/email; case-insensitive substring
-// match keeps the implementation tiny while covering the common
-// "find this person quickly" use case. Server-side search is overkill
-// for the expected per-tenant member counts.
-const filteredMembers = computed(() => {
- const q = searchQuery.value.trim().toLowerCase()
- if (!q) return members.value
- return members.value.filter((m) => {
- return (
- (m.username || '').toLowerCase().includes(q) ||
- (m.email || '').toLowerCase().includes(q)
- )
- })
-})
+function rememberMembersForAudit(rows: TenantMember[]) {
+ for (const m of rows) {
+ memberDisplayByUserId[m.user_id] = { username: m.username, email: m.email }
+ }
+}
async function loadMembers() {
if (!activeTenantId.value) {
- // No active tenant yet — keep silent; the watch below will retry
- // once the auth store finishes hydrating. Showing an error toast
- // on cold-mount would flash on every refresh.
return
}
loading.value = true
error.value = ''
try {
- const resp = await listMembers(activeTenantId.value)
+ const resp = await listMembers(activeTenantId.value, {
+ page: membersPage.value,
+ page_size: membersPageSize.value,
+ q: memberSearchQ.value || undefined,
+ })
if (resp.success && resp.data) {
- members.value = resp.data.members
+ const total = resp.data.total ?? 0
+ const ps = resp.data.page_size ?? membersPageSize.value
+ const safePs = Math.max(1, ps)
+ const maxPage = Math.max(1, Math.ceil(total / safePs))
+ if (membersPage.value > maxPage) {
+ membersPage.value = maxPage
+ loading.value = false
+ await loadMembers()
+ return
+ }
+ members.value = resp.data.members ?? []
+ membersTotal.value = total
+ if (typeof resp.data.page === 'number' && resp.data.page > 0) {
+ membersPage.value = resp.data.page
+ }
+ if (typeof resp.data.page_size === 'number' && resp.data.page_size > 0) {
+ membersPageSize.value = resp.data.page_size
+ }
+ rememberMembersForAudit(members.value)
} else {
error.value = resp.message || t('tenantMember.errors.generic')
}
@@ -465,14 +663,161 @@ async function loadMembers() {
}
}
+function onMembersPageChange() {
+ void loadMembers()
+}
+
+watch(searchQuery, () => {
+ if (!activeTenantId.value) return
+ window.clearTimeout(memberSearchDebounceTimer)
+ memberSearchDebounceTimer = window.setTimeout(() => {
+ memberSearchQ.value = searchQuery.value.trim()
+ membersPage.value = 1
+ loadMembers()
+ }, 320)
+})
+
+// ---- Pending invitations ------------------------------------------------
+
+const invitationColumns = computed(() => [
+ { colKey: 'invitee', title: t('tenantInvitation.columns.invitee'), ellipsis: true, minWidth: 160 },
+ { colKey: 'role', title: t('tenantInvitation.columns.role'), width: 110 },
+ { colKey: 'inviter', title: t('tenantInvitation.columns.inviter'), ellipsis: true, minWidth: 140 },
+ { colKey: 'expires_at', title: t('tenantInvitation.columns.expiresAt'), width: 160 },
+ { colKey: 'status', title: t('tenantInvitation.columns.status'), width: 100 },
+ ...(canManage.value
+ ? [{ colKey: 'actions', title: t('tenantInvitation.columns.operations'), width: 88, align: 'right' as const }]
+ : []),
+])
+
+function invitationStatusTheme(s: TenantInvitation['status']): 'primary' | 'success' | 'warning' | 'danger' | 'default' {
+ switch (s) {
+ case 'pending':
+ return 'primary'
+ case 'accepted':
+ return 'success'
+ case 'declined':
+ case 'revoked':
+ return 'warning'
+ case 'expired':
+ return 'danger'
+ default:
+ return 'default'
+ }
+}
+
+function inviteePrimary(row: TenantInvitation): string {
+ return row.invitee_name?.trim() || row.invitee_email?.trim() || row.invitee_user_id
+}
+
+function inviterPrimary(row: TenantInvitation): string {
+ return row.inviter_name?.trim() || row.inviter_email?.trim() || row.invited_by || '—'
+}
+
+// loadInvitations is called from the same trigger as loadMembers so
+// the Members tab can render the pending section without an extra
+// round-trip latency budget. canManage gates the fetch — viewers /
+// contributors / admins-without-management see no pending section at
+// all (the route returns 200 but listing pending invites to those
+// roles would be UX noise; the route layer is Viewer+ for the read
+// itself).
+async function loadInvitations() {
+ if (!activeTenantId.value || !canManage.value) {
+ invitations.value = []
+ invitationsTotal.value = 0
+ return
+ }
+ invitationsLoading.value = true
+ invitationsError.value = ''
+ try {
+ const resp = await listTenantInvitations(activeTenantId.value, {
+ page: invitationsPage.value,
+ page_size: invitationsPageSize.value,
+ })
+ if (resp.success && resp.data) {
+ const total = resp.data.total ?? 0
+ const ps = resp.data.page_size ?? invitationsPageSize.value
+ const safePs = Math.max(1, ps)
+ const maxPage = Math.max(1, Math.ceil(total / safePs))
+ if (invitationsPage.value > maxPage) {
+ invitationsPage.value = maxPage
+ invitationsLoading.value = false
+ await loadInvitations()
+ return
+ }
+ invitations.value = resp.data.invitations ?? []
+ invitationsTotal.value = total
+ if (typeof resp.data.page === 'number' && resp.data.page > 0) {
+ invitationsPage.value = resp.data.page
+ }
+ if (typeof resp.data.page_size === 'number' && resp.data.page_size > 0) {
+ invitationsPageSize.value = resp.data.page_size
+ }
+ } else {
+ invitationsError.value = resp.message || t('tenantInvitation.errors.generic')
+ }
+ } catch (err: any) {
+ invitationsError.value = err?.message || t('tenantInvitation.errors.generic')
+ } finally {
+ invitationsLoading.value = false
+ }
+}
+
+function onInvitationsPageChange() {
+ void loadInvitations()
+}
+
+// doRevokeInvitation is wired to the t-popconfirm @confirm event in
+// the table template. The popconfirm itself owns the yes/no surface,
+// so this function is the post-confirmation action only — no nested
+// modal. Errors surface as toasts and the row stays in place for retry.
+async function doRevokeInvitation(row: TenantInvitation) {
+ try {
+ const resp = await revokeInvitation(activeTenantId.value, row.id)
+ if (resp.success) {
+ await loadInvitations()
+ MessagePlugin.success(t('tenantInvitation.revoke.success'))
+ } 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 === 409) {
+ MessagePlugin.error(err?.message || t('tenantInvitation.errors.notPending'))
+ } else {
+ MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
+ }
+ }
+}
+
// ---- Audit-log helpers --------------------------------------------------
+/** ellipsis 自带的 Tooltip 默认主题在深色抽屉语境下易产生暗底黑字 */
+const auditTableEllipsisTooltip = { theme: 'light' as const }
+
const auditColumns = computed(() => [
{ colKey: 'created_at', title: t('tenantMember.audit.columns.time'), width: 150 },
- { colKey: 'actor', title: t('tenantMember.audit.columns.actor'), minWidth: 140, ellipsis: true },
+ {
+ colKey: 'actor',
+ title: t('tenantMember.audit.columns.actor'),
+ minWidth: 140,
+ ellipsis: auditTableEllipsisTooltip,
+ },
{ colKey: 'action', title: t('tenantMember.audit.columns.action'), width: 130 },
- { colKey: 'target', title: t('tenantMember.audit.columns.target'), minWidth: 140, ellipsis: true },
- { colKey: 'request_path', title: t('tenantMember.audit.columns.path'), minWidth: 140, ellipsis: true },
+ {
+ colKey: 'target',
+ title: t('tenantMember.audit.columns.target'),
+ minWidth: 140,
+ ellipsis: auditTableEllipsisTooltip,
+ },
+ {
+ colKey: 'request_path',
+ title: t('tenantMember.audit.columns.path'),
+ minWidth: 140,
+ ellipsis: auditTableEllipsisTooltip,
+ },
{ colKey: 'outcome', title: t('tenantMember.audit.columns.outcome'), width: 90 },
])
@@ -504,24 +849,26 @@ function auditOutcomeTheme(o: AuditOutcome): 'success' | 'danger' | 'default' {
return 'default'
}
-// Render a `rbac.member_added` action either via i18n (when the key
-// exists) or as a humanised fallback. The fallback matters because
-// future PRs may push new namespaces (e.g. `kb.shared`) that aren't
-// in the locale file yet — we still want them to render readably.
+// i18n 键名含点号(rbac.member_added)。用 t(path) 会按路径拆开解析,
+// 无法命中 tenantMember.audit.action['rbac.*'] — 必须用 tm + 字面量键。
function formatAuditAction(action: AuditAction): string {
- const key = `tenantMember.audit.action.${action}`
- const translated = t(key)
- if (translated && translated !== key) return translated
+ const bag = tm('tenantMember.audit.action') as unknown
+ if (bag !== null && typeof bag === 'object' && typeof (bag as Record<string, string>)[action] === 'string') {
+ return (bag as Record<string, string>)[action]
+ }
return action
}
-// Resolve a user id to a display name using the already-loaded member
-// list. Falls back to the raw uuid when the actor is no longer a
-// member (e.g. a long-since-removed contributor whose denial events
-// are still on the feed).
+// Resolve a user id to a display label: prefer current页的 members,
+// 再退到历次分页积累的 memberDisplayByUserId,最后是原始 id。
function actorDisplayName(userId: string): string {
- const m = members.value.find((x) => x.user_id === userId)
- return m?.username || m?.email || userId
+ const cur = members.value.find((x) => x.user_id === userId)
+ if (cur?.username?.trim()) return cur.username.trim()
+ if (cur?.email?.trim()) return cur.email.trim()
+ const memo = memberDisplayByUserId[userId]
+ if (memo?.username?.trim()) return memo.username!.trim()
+ if (memo?.email?.trim()) return memo.email!.trim()
+ return userId
}
function formatAuditTarget(row: AuditLog): string {
@@ -588,61 +935,143 @@ async function loadAuditLog(reset: boolean) {
}
}
+function detachAuditInfiniteScroll() {
+ auditScrollObserver?.disconnect()
+ auditScrollObserver = null
+}
+
+function attachAuditInfiniteScroll() {
+ detachAuditInfiniteScroll()
+ const root = auditScrollRoot.value
+ const sentinel = auditLoadSentinelEl.value
+ if (!root || !sentinel) return
+
+ auditScrollObserver = new IntersectionObserver(
+ (entries) => {
+ const hitBottom = entries.some((e) => e.isIntersecting)
+ if (!hitBottom || !auditHasMore.value || auditLoading.value) return
+ void loadAuditLog(false)
+ },
+ { root, rootMargin: '100px 0px', threshold: 0 },
+ )
+ auditScrollObserver.observe(sentinel)
+}
+
function reloadAuditLog() {
auditCursor.value = 0
auditHasMore.value = true
loadAuditLog(true)
}
-// Lazy-load the audit log on first tab switch. Fetching it on every
-// settings-panel mount would waste a request for the (common) case
-// where the operator only wants to manage members.
-watch(activeTab, (tab) => {
- if (tab === 'audit' && !auditLoadedOnce.value) {
+// Lazy-load the audit log the first time the drawer is opened. We
+// avoid watching `auditDrawerVisible` so closing+reopening the drawer
+// doesn't re-fetch behind the user's back — refresh is an explicit
+// action via the drawer's "Refresh" button.
+function openAuditDrawer() {
+ auditDrawerVisible.value = true
+ if (!auditLoadedOnce.value) {
loadAuditLog(true)
}
-})
+}
+
+watch(
+ auditDrawerVisible,
+ async (open) => {
+ if (!open) {
+ detachAuditInfiniteScroll()
+ return
+ }
+ await nextTick()
+ attachAuditInfiniteScroll()
+ },
+ { flush: 'post' },
+)
+
+watch(
+ () => auditError.value,
+ async () => {
+ if (!auditDrawerVisible.value) return
+ await nextTick()
+ if (!auditError.value) {
+ attachAuditInfiniteScroll()
+ return
+ }
+ detachAuditInfiniteScroll()
+ },
+ { flush: 'post' },
+)
+
+onUnmounted(() => detachAuditInfiniteScroll())
-function openAddDialog() {
+watch(invitePopupVisible, (open) => {
+ if (!open) return
addForm.email = ''
addForm.role = 'contributor'
- addDialogVisible.value = true
-}
+ addDialogStep.value = 'form'
+})
+
+// Live display strings for the in-place confirm step. Recomputed
+// every time the user goes Back, tweaks the form, and re-advances —
+// the summary always mirrors the current form state.
+const addConfirmEmail = computed(() => addForm.email.trim())
+const addConfirmRoleLabel = computed(() => t('tenantMember.role.' + addForm.role))
+// submitAdd is wired to the popup footer primary CTA. On step='form' it
+// validates and swaps to summary; on step='confirm' it fires the API.
async function submitAdd() {
- // t-form's validate returns true on success or an object of field
- // errors on failure. Anything other than `true` => keep dialog open
- // with the inline messages shown. The @confirm event lets us control
- // visibility manually; :on-confirm would close on every return.
- const valid = await addFormRef.value?.validate?.()
- if (valid !== true) return
+ if (addDialogStep.value === 'form') {
+ const valid = await addFormRef.value?.validate?.()
+ if (valid !== true) return
+ addDialogStep.value = 'confirm'
+ return
+ }
+ await sendInvitation(addForm.email.trim(), addForm.role)
+}
+// goBackToForm un-advances from confirm to form inside the popup.
+function goBackToForm() {
+ addDialogStep.value = 'form'
+}
+
+// dialogConfirmLabel drives the primary action label across the two steps.
+const dialogConfirmLabel = computed(() =>
+ addDialogStep.value === 'form'
+ ? t('tenantInvitation.inviteSubmit')
+ : t('tenantInvitation.confirmSend'),
+)
+
+// sendInvitation actually fires the create-invitation API call.
+async function sendInvitation(email: string, role: TenantRole) {
adding.value = true
try {
- const resp = await addMember(activeTenantId.value, {
- email: addForm.email.trim(),
- role: addForm.role,
- })
- if (resp.success && resp.data) {
- members.value = [...members.value, resp.data]
- addDialogVisible.value = false
- MessagePlugin.success(t('tenantMember.add.success'))
+ const resp = await createInvitation(activeTenantId.value, { email, role })
+ if (resp.success) {
+ invitationsPage.value = 1
+ await loadInvitations()
+ invitePopupVisible.value = false
+ MessagePlugin.success(t('tenantInvitation.inviteSuccess'))
} else {
- MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
+ MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
}
} catch (err: any) {
- // The axios interceptor already flattens errors to
- // { status, message, error?, ... }, so we read err.status directly
- // — err.response.status is undefined here.
const status = err?.status
if (status === 404) {
MessagePlugin.error(t('tenantMember.errors.userNotFound'))
} else if (status === 409) {
- MessagePlugin.error(t('tenantMember.errors.alreadyMember'))
+ // Server returns the same 409 for both "already a member" and
+ // "already a pending invite". The message body discriminates,
+ // but for the toast we show both possibilities folded into one
+ // helpful line.
+ MessagePlugin.error(
+ err?.message ||
+ `${t('tenantInvitation.errors.alreadyMember')} / ${t(
+ 'tenantInvitation.errors.pendingExists',
+ )}`,
+ )
} else if (status === 400) {
MessagePlugin.error(err?.message || t('tenantMember.errors.invalidRole'))
} else {
- MessagePlugin.error(err?.message || t('tenantMember.errors.generic'))
+ MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
}
} finally {
adding.value = false
@@ -657,7 +1086,23 @@ async function onRoleChange(row: TenantMember, newRole: string) {
try {
const resp = await updateMemberRole(activeTenantId.value, row.user_id, next)
if (resp.success) {
- row.role = next
+ // Mutate the row by replacing it in `members.value` instead of
+ // assigning `row.role = next` in place. The `row` argument here
+ // is the row object handed in by t-table's slot scope, which in
+ // some TDesign versions is a shallow copy that doesn't share
+ // reactivity with the `members` array — assigning `row.role`
+ // updates the local handle but not the rendered cell, so the
+ // select keeps showing the previous value until a refresh.
+ // Splicing a fresh object into the source array guarantees the
+ // table re-renders.
+ const idx = members.value.findIndex((m) => m.user_id === row.user_id)
+ if (idx >= 0) {
+ const merged = { ...members.value[idx], role: next }
+ members.value.splice(idx, 1, merged)
+ rememberMembersForAudit([merged])
+ } else {
+ row.role = next
+ }
MessagePlugin.success(t('tenantMember.roleChange.success'))
return
}
@@ -689,7 +1134,7 @@ function confirmRemove(row: TenantMember) {
try {
const resp = await removeMember(activeTenantId.value, row.user_id)
if (resp.success) {
- members.value = members.value.filter((m) => m.user_id !== row.user_id)
+ await loadMembers()
MessagePlugin.success(t('tenantMember.remove.success'))
} else {
MessagePlugin.error(resp.message || t('tenantMember.errors.generic'))
@@ -718,14 +1163,22 @@ function confirmRemove(row: TenantMember) {
watch(
activeTenantId,
(id) => {
- if (id) loadMembers()
+ if (id) {
+ searchQuery.value = ''
+ memberSearchQ.value = ''
+ window.clearTimeout(memberSearchDebounceTimer)
+ membersPage.value = 1
+ invitationsPage.value = 1
+ membersPageSize.value = 20
+ invitationsPageSize.value = 20
+ membersTotal.value = 0
+ invitationsTotal.value = 0
+ loadMembers()
+ loadInvitations()
+ }
},
{ immediate: true },
)
-
-onMounted(() => {
- if (activeTenantId.value) loadMembers()
-})
</script>
<style lang="less" scoped>
@@ -766,7 +1219,7 @@ onMounted(() => {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 6px 0;
+ margin: 0;
letter-spacing: -0.02em;
}
@@ -774,24 +1227,30 @@ onMounted(() => {
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 1.55;
- margin: 0;
+ margin: 6px 0 0 0;
max-width: 52rem;
}
}
-.tenant-members-tabs {
- :deep(.t-tabs__nav-scroll-container) {
- margin-bottom: 2px;
- }
+.section-header-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+}
- :deep(.t-tabs__nav-item) {
- height: 40px;
- line-height: 40px;
- }
+.section-header-titlewrap {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+}
- :deep(.t-tab-panel) {
- padding-top: 4px;
- }
+/* 顶部右侧的「审计日志」入口。t-button variant="text" 自带颜色
+ 交互;这里只调 flex 行为,避免在 wrap 时被挤压。 */
+.header-audit-btn {
+ flex-shrink: 0;
}
.members-tab-layout {
@@ -799,45 +1258,52 @@ onMounted(() => {
flex-direction: column;
}
-.members-toolbar {
+/* 带子分页的卡片:仅在表格主体上横向滚动,页脚不参与滚动,避免分页条被卷入或对齐错位。
+ 双类选择器用于盖过根上 .data-table-shell 的 overflow-x: auto */
+.data-table-shell.data-table-shell--with-footer {
display: flex;
flex-direction: column;
- gap: 14px;
- margin-bottom: 20px;
-}
-
-.toolbar-meta {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 8px 12px;
- min-height: 32px;
+ overflow: hidden;
- .toolbar-count {
- font-size: 13px;
- font-weight: 500;
- color: var(--td-text-color-secondary);
+ >.data-table-shell__scroll {
+ overflow-x: auto;
+ min-width: 0;
}
- .toolbar-meta-sep {
+ >.data-table-shell__pager {
flex-shrink: 0;
- width: 1px;
- height: 14px;
- background-color: var(--td-component-border);
- opacity: 0.72;
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ padding: 10px 14px;
+ border-top: 1px solid var(--td-component-stroke);
+ background-color: var(--td-bg-color-container);
+
+ :deep(.t-pagination) {
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ row-gap: 8px;
+ }
}
}
+/* 待接受区块整体为浅底色,分页条与表格区同色阶、仅靠顶部分割线与表格区分 */
+.pending-invitations-table.data-table-shell.data-table-shell--with-footer>.data-table-shell__pager {
+ background-color: transparent;
+}
+
.permissions-trigger-btn {
display: inline-flex;
align-items: center;
justify-content: center;
- width: 32px;
- height: 32px;
+ width: 28px;
+ height: 28px;
margin: 0;
padding: 0;
border: none;
- border-radius: 8px;
+ border-radius: 6px;
background: transparent;
color: var(--td-text-color-secondary);
cursor: pointer;
@@ -854,62 +1320,92 @@ onMounted(() => {
}
}
-.toolbar-controls {
- display: block;
+/* 列表上方的标题行:「空间成员 [N] · 筛选出 K」 左侧;右侧
+ 是「搜索 + 邀请按钮」一组。视觉级别与「待接受邀请」一致。 */
+.members-list-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
}
-.toolbar-actions-bar {
+.members-list-header {
display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 0 2px;
flex-wrap: wrap;
+}
+
+.members-list-titlewrap {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.members-list-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+}
+
+/* 数字外面套一个浅底圆角徽章,避免裸露的「成员 1」读起来像
+ 排版残留。色阶与 td-tag default+light 看齐。 */
+.members-list-count-badge {
+ display: inline-flex;
align-items: center;
- gap: 10px 12px;
- padding: 8px 12px;
+ justify-content: center;
+ min-width: 22px;
+ height: 20px;
+ padding: 0 7px;
+ border-radius: 10px;
background-color: var(--td-bg-color-secondarycontainer);
- border: 1px solid var(--td-component-border);
- border-radius: 8px;
- box-sizing: border-box;
+ color: var(--td-text-color-primary);
+ font-size: 12px;
+ font-weight: 600;
+ line-height: 1;
}
-.toolbar-search {
- flex: 1 1 12rem;
+.members-list-filter-hint {
+ font-size: 12px;
+ color: var(--td-text-color-secondary);
+}
+
+.members-list-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ flex: 0 1 auto;
min-width: 0;
- max-width: 22rem;
+}
- :deep(.t-input),
- .toolbar-search-input {
- width: 100%;
- }
+.members-list-search {
+ flex: 0 1 14rem;
+ min-width: 8rem;
+ max-width: 16rem;
- &:deep(.t-input__prefix)>.t-icon {
- align-self: center;
+ :deep(.t-input) {
+ width: 100%;
}
}
-.toolbar-btn-group {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 10px;
+/* 列表头的邀请按钮:outline + primary,自带外框,比裸 icon
+ 有分量;shape="square" 让它仍然是个紧凑的图标按钮。 */
+.members-list-add-btn {
flex-shrink: 0;
}
@media (max-width: 560px) {
- .toolbar-actions-bar {
- flex-direction: column;
- align-items: stretch;
- gap: 10px;
+ .members-list-actions {
+ width: 100%;
+ justify-content: flex-start;
}
- .toolbar-search {
- flex-basis: auto;
+ .members-list-search {
+ flex: 1 1 auto;
max-width: none;
}
-
- .toolbar-btn-group {
- justify-content: flex-end;
- flex-wrap: nowrap;
- gap: 8px;
- }
}
.data-table-shell {
@@ -929,24 +1425,29 @@ onMounted(() => {
padding-bottom: 12px;
}
- /* 角色列:下拉不要超过单元格,避免外层 overflow-x 把右边框裁没 */
+ /* 角色列:下拉收缩到内容宽度,不再撑满整格。原先 100% 在窄角色
+ 名(如"Owner")下显得空荡且与其他列对不齐。 */
&:deep(.role-cell) {
display: flex;
align-items: center;
- width: 100%;
- max-width: 100%;
min-width: 0;
box-sizing: border-box;
}
&:deep(.member-role-select.t-select),
&:deep(.member-role-select.t-select > .t-select__wrap) {
- flex: 1 1 auto;
- width: 100%;
- max-width: 100%;
+ flex: 0 0 auto;
+ width: 92px;
min-width: 0;
box-sizing: border-box;
}
+
+ /* 收紧 select 内部 padding,让最长角色名 "Contributor" 也能在
+ 92px 内显示而不被中点截掉。 */
+ &:deep(.member-role-select .t-input) {
+ padding-left: 8px;
+ padding-right: 4px;
+ }
}
.permissions-compact {
@@ -1118,6 +1619,88 @@ onMounted(() => {
padding: 20px 0 8px;
}
+/* Invite popup: confirm copy + footer actions (anchored beside +). */
+.member-invite-popup-inner {
+ max-width: 100%;
+}
+
+.member-invite-popup-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0 0 12px;
+ line-height: 1.35;
+}
+
+.member-invite-form {
+ &:deep(.t-form__item) {
+ margin-bottom: 14px;
+
+ &:last-child {
+ margin-bottom: 4px;
+ }
+ }
+}
+
+.invite-confirm-body {
+ padding: 4px 0 8px;
+ color: var(--td-text-color-primary);
+ font-size: 14px;
+ line-height: 1.6;
+}
+
+.invite-popup-footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 16px;
+}
+
+.pending-invitations-section {
+ margin-bottom: 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+
+ .pending-invitations-header {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .pending-invitations-titlewrap {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .pending-invitations-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ }
+
+ .pending-invitations-desc {
+ font-size: 12px;
+ color: var(--td-text-color-secondary);
+ }
+
+ .pending-invitations-empty {
+ padding: 10px 12px;
+ border: 1px dashed var(--td-component-stroke);
+ border-radius: 8px;
+ color: var(--td-text-color-secondary);
+ font-size: 13px;
+ background: var(--td-bg-color-container);
+ }
+
+ /* Visually distinguish from members table so the eye doesn't fuse
+ "pending" rows with "actual member" rows. */
+ .pending-invitations-table {
+ background: var(--td-bg-color-secondarycontainer);
+ }
+}
+
.empty-state {
padding: 40px 0 16px;
display: flex;
@@ -1131,6 +1714,13 @@ onMounted(() => {
padding-top: 8px;
}
+/* Inside the drawer the t-drawer body already gives us padding, so
+ drop the top offset; otherwise the audit-header floats away from
+ the drawer title with no visual anchor. */
+.audit-panel--drawer {
+ padding-top: 0;
+}
+
.audit-header {
display: flex;
align-items: center;
@@ -1141,9 +1731,86 @@ onMounted(() => {
gap: 12px;
.audit-desc {
+ flex: 1;
+ min-width: 0;
font-size: 13px;
color: var(--td-text-color-secondary);
}
+
+ .audit-refresh-btn {
+ flex-shrink: 0;
+ }
+}
+
+.audit-drawer-inner {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ gap: 14px;
+ min-height: 0;
+ width: 100%;
+ box-sizing: border-box;
+}
+
+.audit-drawer-fill {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.audit-drawer-branch {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+}
+
+.audit-drawer-branch--error {
+ justify-content: center;
+
+ .error-inline {
+ width: 100%;
+ }
+}
+
+.audit-drawer-branch--empty.empty-state--audit {
+ flex: 1 1 auto;
+ justify-content: center;
+ align-items: center;
+ padding: 24px 12px;
+ min-height: 0;
+}
+
+.audit-scroll-area {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-x: hidden;
+ overflow-y: auto;
+}
+
+.audit-load-sentinel {
+ height: 1px;
+ width: 100%;
+ pointer-events: none;
+}
+
+.audit-loading-more {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ padding: 12px;
+ font-size: 12px;
+ color: var(--td-text-color-secondary);
+}
+
+.audit-end-hint {
+ text-align: center;
+ font-size: 12px;
+ color: var(--td-text-color-disabled);
+ padding: 8px 0 14px;
+ margin: 0;
}
.audit-actor {
@@ -1174,17 +1841,58 @@ onMounted(() => {
margin-right: 4px;
}
}
+</style>
+
+<style lang="less">
+/* t-popup 挂到 body,需全局样式;z-index 需高于设置全屏遮罩(2000)。 */
+.member-invite-popup-overlay {
+ z-index: 3050 !important;
+
+ .t-popup__content {
+ padding: 14px 16px !important;
+ min-width: 300px;
+ max-width: min(392px, calc(100vw - 24px));
+ border-radius: 12px !important;
+ background: var(--td-bg-color-container) !important;
+ border: 0.5px solid var(--td-component-stroke) !important;
+ box-shadow:
+ 0 0 0 0.5px rgba(0, 0, 0, 0.03),
+ 0 2px 4px rgba(0, 0, 0, 0.04),
+ 0 8px 24px rgba(0, 0, 0, 0.1) !important;
+ backdrop-filter: blur(20px) saturate(180%) !important;
+ -webkit-backdrop-filter: blur(20px) saturate(180%) !important;
+ }
+}
-.audit-footer {
+:root[theme-mode='dark'] .member-invite-popup-overlay .t-popup__content {
+ background: rgba(36, 36, 36, 0.92) !important;
+ border-color: rgba(255, 255, 255, 0.08) !important;
+ box-shadow:
+ 0 0 0 0.5px rgba(255, 255, 255, 0.05),
+ 0 2px 4px rgba(0, 0, 0, 0.12),
+ 0 8px 32px rgba(0, 0, 0, 0.28) !important;
+}
+
+/* 角色下拉挂到 body 时可能被邀请 Popup / 设置遮罩盖住,类名挂在 t-popup 根节点 */
+.tenant-members-role-select-popup {
+ z-index: 6200 !important;
+}
+
+/* 成员页审计抽屉 teleport 到 body,须全局样式才能把 body 高度链拉满以便内层滚动 */
+.t-drawer.tenant-members-audit-drawer.t-drawer--right .t-drawer__content-wrapper--right {
+ box-sizing: border-box;
display: flex;
- justify-content: center;
- align-items: center;
- padding: 8px 0 4px;
- margin-top: 4px;
+ flex-direction: column;
+ max-height: 100vh;
+ height: 100%;
+}
- .audit-end {
- font-size: 12px;
- color: var(--td-text-color-disabled);
- }
+.t-drawer.tenant-members-audit-drawer .t-drawer__body {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ box-sizing: border-box;
+ overflow: hidden !important;
}
</style>
diff --git a/internal/application/repository/tenant_invitation.go b/internal/application/repository/tenant_invitation.go
new file mode 100644
index 000000000..a135e8340
--- /dev/null
+++ b/internal/application/repository/tenant_invitation.go
@@ -0,0 +1,257 @@
+package repository
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "gorm.io/gorm"
+)
+
+// ErrPendingInvitationExists is returned by Create when a pending
+// invitation for (tenant_id, invitee_user_id) already exists. The
+// service layer maps it to its own sentinel for the handler.
+var ErrPendingInvitationExists = errors.New("repository: pending invitation already exists")
+
+// tenantInvitationRepository implements interfaces.TenantInvitationRepository.
+type tenantInvitationRepository struct {
+ db *gorm.DB
+}
+
+// NewTenantInvitationRepository constructs the repo against db. Wired
+// up via the dig container alongside other repositories.
+func NewTenantInvitationRepository(db *gorm.DB) interfaces.TenantInvitationRepository {
+ return &tenantInvitationRepository{db: db}
+}
+
+// Create inserts a new pending invitation row. The partial unique
+// index on (tenant_id, invitee_user_id) WHERE status='pending' is the
+// authoritative guard against duplicates, but we ALSO pre-check via
+// GetPendingByPair inside a tiny transaction so the typical "click
+// twice fast" case returns a clean sentinel instead of a raw 23505 /
+// SQLITE_CONSTRAINT error string the handler would have to parse.
+//
+// The pre-check is best-effort: two concurrent inserts can still race
+// past it, in which case the underlying database error surfaces. The
+// service layer treats any insert error containing the index name
+// (idx_tenant_invitations_unique_pending) as the conflict sentinel —
+// see invitationService.Create.
+func (r *tenantInvitationRepository) Create(
+ ctx context.Context,
+ inv *types.TenantInvitation,
+) error {
+ if inv.Status == "" {
+ inv.Status = types.TenantInvitationStatusPending
+ }
+ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ var probe types.TenantInvitation
+ err := tx.
+ Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
+ inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
+ First(&probe).Error
+ switch {
+ case errors.Is(err, gorm.ErrRecordNotFound):
+ // fallthrough — clean to insert.
+ case err != nil:
+ return err
+ default:
+ return ErrPendingInvitationExists
+ }
+ return tx.Create(inv).Error
+ })
+}
+
+// GetByID returns the invitation row (regardless of status) or
+// (nil, nil) when missing. Used by Accept/Decline/Revoke flows that
+// must inspect status before transitioning.
+func (r *tenantInvitationRepository) GetByID(
+ ctx context.Context,
+ id uint64,
+) (*types.TenantInvitation, error) {
+ var inv types.TenantInvitation
+ err := r.db.WithContext(ctx).Where("id = ?", id).First(&inv).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &inv, nil
+}
+
+// GetPendingByPair returns the in-flight pending invitation, if any.
+func (r *tenantInvitationRepository) GetPendingByPair(
+ ctx context.Context,
+ tenantID uint64,
+ inviteeUserID string,
+) (*types.TenantInvitation, error) {
+ var inv types.TenantInvitation
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
+ tenantID, inviteeUserID, types.TenantInvitationStatusPending).
+ First(&inv).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &inv, nil
+}
+
+// listQuery centralises the "newest-first" ordering and includeTerminal
+// filter so ListByTenant / ListByInvitee stay short.
+func (r *tenantInvitationRepository) listQuery(includeTerminal bool) *gorm.DB {
+ q := r.db.Order("id DESC")
+ if !includeTerminal {
+ q = q.Where("status = ?", types.TenantInvitationStatusPending)
+ }
+ return q
+}
+
+// tenantInvitationTenantScope applies tenant_id, optional pending-only
+// filter, and id DESC ordering — shared by ListByTenant and paging helpers.
+func (r *tenantInvitationRepository) tenantInvitationTenantScope(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+) *gorm.DB {
+ q := r.db.WithContext(ctx).
+ Model(&types.TenantInvitation{}).
+ Where("tenant_id = ?", tenantID).
+ Order("id DESC")
+ if !includeTerminal {
+ q = q.Where("status = ?", types.TenantInvitationStatusPending)
+ }
+ return q
+}
+
+// ListByTenant returns invitations for the tenant ordered by id DESC.
+func (r *tenantInvitationRepository) ListByTenant(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ var rows []*types.TenantInvitation
+ err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return rows, nil
+}
+
+// CountByTenantList counts invitations matching ListByTenant filters.
+func (r *tenantInvitationRepository) CountByTenantList(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+) (int64, error) {
+ var n int64
+ err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
+ Count(&n).Error
+ return n, err
+}
+
+// ListByTenantPage returns a page of invitations (id DESC).
+func (r *tenantInvitationRepository) ListByTenantPage(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+ offset, limit int,
+) ([]*types.TenantInvitation, error) {
+ var rows []*types.TenantInvitation
+ err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
+ Offset(offset).
+ Limit(limit).
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return rows, nil
+}
+
+// ListByInvitee returns invitations addressed to the user across all
+// tenants.
+func (r *tenantInvitationRepository) ListByInvitee(
+ ctx context.Context,
+ inviteeUserID string,
+ includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ var rows []*types.TenantInvitation
+ err := r.listQuery(includeTerminal).
+ WithContext(ctx).
+ Where("invitee_user_id = ?", inviteeUserID).
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ return rows, nil
+}
+
+// CountPendingByInvitee returns the pending invitation count for the user.
+func (r *tenantInvitationRepository) CountPendingByInvitee(
+ ctx context.Context,
+ inviteeUserID string,
+) (int64, error) {
+ var count int64
+ err := r.db.WithContext(ctx).
+ Model(&types.TenantInvitation{}).
+ Where("invitee_user_id = ? AND status = ?",
+ inviteeUserID, types.TenantInvitationStatusPending).
+ Count(&count).Error
+ return count, err
+}
+
+// MarkStatusIfPending atomically transitions a row from pending to
+// the supplied terminal status. The WHERE filter on status='pending'
+// is what makes this safe under concurrent accept/revoke clicks —
+// only the first writer succeeds; the second sees RowsAffected=0 and
+// receives gorm.ErrRecordNotFound (which the service maps to a
+// "already finalised" sentinel).
+func (r *tenantInvitationRepository) MarkStatusIfPending(
+ ctx context.Context,
+ id uint64,
+ status types.TenantInvitationStatus,
+ respondedAt time.Time,
+) error {
+ res := r.db.WithContext(ctx).
+ Model(&types.TenantInvitation{}).
+ Where("id = ? AND status = ?", id, types.TenantInvitationStatusPending).
+ Updates(map[string]any{
+ "status": status,
+ "responded_at": respondedAt,
+ "updated_at": time.Now(),
+ })
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return gorm.ErrRecordNotFound
+ }
+ return nil
+}
+
+// SweepExpired transitions all overdue pending rows to expired in a
+// single batch. We intentionally don't emit per-row audit events from
+// here — the original rbac.invitation_sent already lives in the audit
+// log, and a sweep can touch many rows on a sleepy weekend (an audit
+// fanout would dwarf the original event volume).
+func (r *tenantInvitationRepository) SweepExpired(
+ ctx context.Context,
+ now time.Time,
+) (int64, error) {
+ res := r.db.WithContext(ctx).
+ Model(&types.TenantInvitation{}).
+ Where("status = ? AND expires_at < ?", types.TenantInvitationStatusPending, now).
+ Updates(map[string]any{
+ "status": types.TenantInvitationStatusExpired,
+ "responded_at": now,
+ "updated_at": time.Now(),
+ })
+ if res.Error != nil {
+ return 0, res.Error
+ }
+ return res.RowsAffected, nil
+}
diff --git a/internal/application/repository/tenant_member.go b/internal/application/repository/tenant_member.go
index 303dd1bce..71a68aee6 100644
--- a/internal/application/repository/tenant_member.go
+++ b/internal/application/repository/tenant_member.go
@@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
+ "strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -92,6 +93,56 @@ func (r *tenantMemberRepository) ListByTenant(ctx context.Context, tenantID uint
return members, nil
}
+// CountFilteredByTenant counts active tenant membership rows, optionally
+// restricted to users whose email or username matches search.
+func (r *tenantMemberRepository) CountFilteredByTenant(
+ ctx context.Context, tenantID uint64, search string,
+) (int64, error) {
+ search = strings.TrimSpace(search)
+ q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
+ Where("tenant_id = ?", tenantID)
+ var total int64
+ var err error
+ if search == "" {
+ err = q.Count(&total).Error
+ } else {
+ like := "%" + escapeLikePattern(search) + "%"
+ err = q.
+ Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
+ Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
+ Count(&total).Error
+ }
+ return total, err
+}
+
+// ListPagedByTenant lists active memberships with stable sort.
+func (r *tenantMemberRepository) ListPagedByTenant(
+ ctx context.Context, tenantID uint64, search string, offset, limit int,
+) ([]*types.TenantMember, error) {
+ search = strings.TrimSpace(search)
+ var members []*types.TenantMember
+ q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
+ Where("tenant_id = ?", tenantID).
+ Order("tenant_members.joined_at ASC, tenant_members.id ASC").
+ Offset(offset).
+ Limit(limit)
+
+ var err error
+ if search == "" {
+ err = q.Find(&members).Error
+ } else {
+ like := "%" + escapeLikePattern(search) + "%"
+ err = q.
+ Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
+ Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
+ Find(&members).Error
+ }
+ if err != nil {
+ return nil, err
+ }
+ return members, nil
+}
+
// UpdateRole changes the role of an existing active membership.
func (r *tenantMemberRepository) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
res := r.db.WithContext(ctx).
diff --git a/internal/application/service/tenant_invitation.go b/internal/application/service/tenant_invitation.go
new file mode 100644
index 000000000..c6ed4194c
--- /dev/null
+++ b/internal/application/service/tenant_invitation.go
@@ -0,0 +1,430 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "strconv"
+ "time"
+
+ apprepo "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// Sentinel errors returned by tenantInvitationService. Callers compare
+// with errors.Is to render the appropriate HTTP responses.
+var (
+ // ErrInvitationNotFound is returned when no invitation row matches
+ // the supplied id.
+ ErrInvitationNotFound = errors.New("invitation not found")
+
+ // ErrPendingInvitationExists is returned by Create when a pending
+ // invitation for (tenant, invitee) is already in flight. The
+ // handler maps this to 409.
+ ErrPendingInvitationExists = errors.New("a pending invitation for this user already exists")
+
+ // ErrAlreadyMember is returned by Create when the invitee is
+ // already an active member of the tenant; sending an invite would
+ // be a no-op at best and a confusing UX at worst.
+ ErrAlreadyMember = errors.New("user is already an active member of the tenant")
+
+ // ErrInvitationNotPending is returned by Accept / Decline / Revoke
+ // when the row exists but has already been finalised. Maps to 409.
+ ErrInvitationNotPending = errors.New("invitation is no longer pending")
+
+ // ErrInvitationExpired is returned by Accept / Decline when the
+ // pending row has aged past its expires_at. Maps to 410.
+ ErrInvitationExpired = errors.New("invitation has expired")
+
+ // ErrInvitationForbidden is returned by Accept / Decline when the
+ // caller is not the invitee. Owner-driven Revoke is gated at the
+ // route layer so this error only surfaces on the /me/ paths.
+ ErrInvitationForbidden = errors.New("only the invitee can accept or decline this invitation")
+)
+
+// defaultInvitationTTL is the lifetime of a pending invitation before
+// the lazy sweep transitions it to expired. Operator override is via
+// the WEKNORA_INVITATION_TTL env var (Go duration: "168h", "7d-ish");
+// keeping this out of TenantConfig avoids a yaml migration for a knob
+// that almost nobody is going to tweak.
+const defaultInvitationTTL = 7 * 24 * time.Hour
+
+// invitationTTL resolves the effective TTL at call time so an operator
+// can hot-reload the override without restarting. The env var is parsed
+// once per call; cost is negligible and beats a goroutine watching the
+// environment.
+func invitationTTL() time.Duration {
+ raw := os.Getenv("WEKNORA_INVITATION_TTL")
+ if raw == "" {
+ return defaultInvitationTTL
+ }
+ if d, err := time.ParseDuration(raw); err == nil && d > 0 {
+ return d
+ }
+ // Allow "604800" seconds for callers that don't like Go duration
+ // syntax — same shape as the rest of our int env knobs.
+ if secs, err := strconv.ParseInt(raw, 10, 64); err == nil && secs > 0 {
+ return time.Duration(secs) * time.Second
+ }
+ return defaultInvitationTTL
+}
+
+// tenantInvitationService implements interfaces.TenantInvitationService.
+type tenantInvitationService struct {
+ repo interfaces.TenantInvitationRepository
+ memberSvc interfaces.TenantMemberService
+ audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
+ now func() time.Time // injection seam for tests
+}
+
+// NewTenantInvitationService wires the dependencies. memberSvc is
+// required (Accept must create the tenant_members row); audit is
+// optional and matches the same nil-safe pattern tenantMemberService
+// uses.
+func NewTenantInvitationService(
+ repo interfaces.TenantInvitationRepository,
+ memberSvc interfaces.TenantMemberService,
+ audit interfaces.AuditLogService,
+) interfaces.TenantInvitationService {
+ return &tenantInvitationService{
+ repo: repo,
+ memberSvc: memberSvc,
+ audit: audit,
+ now: time.Now,
+ }
+}
+
+// emitAudit is the best-effort audit hook; mirrors tenantMemberService.
+func (s *tenantInvitationService) emitAudit(ctx context.Context, entry *types.AuditLog) {
+ if s.audit == nil {
+ return
+ }
+ _ = s.audit.Log(ctx, entry)
+}
+
+// detailsFor packs the role + invitation id into the audit Details so a
+// reader can reconstruct "Alice invited Bob as Admin (inv #42)" without
+// joining back to the invitations table.
+func detailsFor(invID uint64, role types.TenantRole) types.JSON {
+ b, _ := json.Marshal(map[string]any{
+ "invitation_id": invID,
+ "role": string(role),
+ })
+ return types.JSON(b)
+}
+
+// sweep transitions overdue pending rows to expired before any List/
+// Accept/Decline/Count read. Failures are logged and swallowed — a
+// transient sweep error must not block a user from reading their
+// inbox; the next call will sweep again.
+func (s *tenantInvitationService) sweep(ctx context.Context) {
+ if _, err := s.repo.SweepExpired(ctx, s.now()); err != nil {
+ logger.Warnf(ctx, "tenant_invitation lazy sweep failed: %v", err)
+ }
+}
+
+// Create issues a new pending invitation. Returns the standard
+// conflict sentinels for the duplicate-pending and already-member
+// cases.
+func (s *tenantInvitationService) Create(
+ ctx context.Context,
+ tenantID uint64,
+ inviteeUserID string,
+ role types.TenantRole,
+ invitedBy *string,
+ message string,
+) (*types.TenantInvitation, error) {
+ if !role.IsValid() {
+ return nil, ErrInvalidTenantRole
+ }
+ // Reject early if the invitee is already an active member; the
+ // handler renders this as "they're already in" rather than the
+ // generic conflict.
+ existing, err := s.memberSvc.GetMembership(ctx, inviteeUserID, tenantID)
+ if err != nil {
+ return nil, err
+ }
+ if existing != nil && existing.Status == types.TenantMemberStatusActive {
+ return nil, ErrAlreadyMember
+ }
+
+ now := s.now()
+ inv := &types.TenantInvitation{
+ TenantID: tenantID,
+ InviteeUserID: inviteeUserID,
+ InvitedBy: invitedBy,
+ Role: role,
+ Status: types.TenantInvitationStatusPending,
+ Message: message,
+ ExpiresAt: now.Add(invitationTTL()),
+ }
+ if err := s.repo.Create(ctx, inv); err != nil {
+ if errors.Is(err, apprepo.ErrPendingInvitationExists) {
+ return nil, ErrPendingInvitationExists
+ }
+ return nil, err
+ }
+
+ s.emitAudit(ctx, &types.AuditLog{
+ TenantID: tenantID,
+ ActorUserID: auditActor(ctx),
+ ActorRole: auditActorRole(ctx),
+ Action: types.AuditActionInvitationSent,
+ TargetType: "tenant_invitation",
+ TargetID: strconv.FormatUint(inv.ID, 10),
+ TargetUserID: inviteeUserID,
+ Outcome: types.AuditOutcomeSuccess,
+ Details: detailsFor(inv.ID, role),
+ })
+ return inv, nil
+}
+
+// Accept transitions a pending invitation into accepted AND creates
+// the active tenant_members row in the same flow. We do NOT wrap both
+// writes in a single DB transaction because TenantMemberService.AddMember
+// owns its own write + audit emit and reaching across services here
+// would force the audit-log writes to commit/rollback in lockstep.
+// Instead, we order operations so the user-visible failure mode is
+// "you couldn't accept the invitation"; if the membership insert fails
+// AFTER the invitation transition committed (rare; collision on the
+// tenant_members unique index would be the only realistic case), the
+// row already in tenant_members wins and a subsequent Accept call sees
+// ErrInvitationNotPending which the handler renders as 409.
+func (s *tenantInvitationService) Accept(
+ ctx context.Context,
+ invID uint64,
+ callerUserID string,
+) (*types.TenantMember, error) {
+ s.sweep(ctx)
+
+ inv, err := s.repo.GetByID(ctx, invID)
+ if err != nil {
+ return nil, err
+ }
+ if inv == nil {
+ return nil, ErrInvitationNotFound
+ }
+ if inv.InviteeUserID != callerUserID {
+ return nil, ErrInvitationForbidden
+ }
+ if inv.Status != types.TenantInvitationStatusPending {
+ return nil, ErrInvitationNotPending
+ }
+ if inv.IsExpired(s.now()) {
+ // The sweep above should have flipped it already, but a row
+ // can age past expires_at between the sweep and this read.
+ // Treat it as expired regardless.
+ return nil, ErrInvitationExpired
+ }
+
+ now := s.now()
+ if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusAccepted, now); err != nil {
+ // Another goroutine (concurrent click) won the race. Honour
+ // the state machine.
+ return nil, ErrInvitationNotPending
+ }
+
+ // Create the actual tenant_members row. Cross-service hop: the
+ // member service handles its own audit (rbac.member_added) and
+ // also enforces the (user, tenant) uniqueness invariant via the
+ // repo. If it fails here the invitation is already accepted —
+ // see comment above for why we don't rollback the invitation.
+ member, err := s.memberSvc.AddMember(ctx, inv.InviteeUserID, inv.TenantID, inv.Role, inv.InvitedBy)
+ if err != nil {
+ // Special-case "already a member": that's the idempotent
+ // outcome we want. Return the existing membership instead of
+ // bubbling the error up to the invitee.
+ if errors.Is(err, ErrMembershipAlreadyExists) {
+ existing, getErr := s.memberSvc.GetMembership(ctx, inv.InviteeUserID, inv.TenantID)
+ if getErr == nil && existing != nil {
+ s.emitInvitationAccepted(ctx, inv)
+ return existing, nil
+ }
+ }
+ logger.Errorf(ctx,
+ "invitation %d accepted but tenant_members insert failed: %v",
+ invID, err)
+ return nil, err
+ }
+
+ s.emitInvitationAccepted(ctx, inv)
+ return member, nil
+}
+
+// emitInvitationAccepted writes the rbac.invitation_accepted audit row.
+// Actor is the invitee (acting on their own inbox); target is the same
+// user since the action is self-directed.
+func (s *tenantInvitationService) emitInvitationAccepted(ctx context.Context, inv *types.TenantInvitation) {
+ s.emitAudit(ctx, &types.AuditLog{
+ TenantID: inv.TenantID,
+ ActorUserID: auditActor(ctx),
+ ActorRole: auditActorRole(ctx),
+ Action: types.AuditActionInvitationAccepted,
+ TargetType: "tenant_invitation",
+ TargetID: strconv.FormatUint(inv.ID, 10),
+ TargetUserID: inv.InviteeUserID,
+ Outcome: types.AuditOutcomeSuccess,
+ Details: detailsFor(inv.ID, inv.Role),
+ })
+}
+
+// Decline transitions the pending row into declined. Only the invitee
+// themselves can call this.
+func (s *tenantInvitationService) Decline(
+ ctx context.Context,
+ invID uint64,
+ callerUserID string,
+) error {
+ s.sweep(ctx)
+
+ inv, err := s.repo.GetByID(ctx, invID)
+ if err != nil {
+ return err
+ }
+ if inv == nil {
+ return ErrInvitationNotFound
+ }
+ if inv.InviteeUserID != callerUserID {
+ return ErrInvitationForbidden
+ }
+ if inv.Status != types.TenantInvitationStatusPending {
+ return ErrInvitationNotPending
+ }
+ if inv.IsExpired(s.now()) {
+ return ErrInvitationExpired
+ }
+
+ if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusDeclined, s.now()); err != nil {
+ return ErrInvitationNotPending
+ }
+
+ s.emitAudit(ctx, &types.AuditLog{
+ TenantID: inv.TenantID,
+ ActorUserID: auditActor(ctx),
+ ActorRole: auditActorRole(ctx),
+ Action: types.AuditActionInvitationDeclined,
+ TargetType: "tenant_invitation",
+ TargetID: strconv.FormatUint(inv.ID, 10),
+ TargetUserID: inv.InviteeUserID,
+ Outcome: types.AuditOutcomeSuccess,
+ Details: detailsFor(inv.ID, inv.Role),
+ })
+ return nil
+}
+
+// Revoke transitions the pending row into revoked. Route-layer Owner
+// gate guarantees the caller is allowed to act on this tenant; this
+// method does not re-check role.
+func (s *tenantInvitationService) Revoke(ctx context.Context, invID uint64) error {
+ s.sweep(ctx)
+
+ inv, err := s.repo.GetByID(ctx, invID)
+ if err != nil {
+ return err
+ }
+ if inv == nil {
+ return ErrInvitationNotFound
+ }
+ if inv.Status != types.TenantInvitationStatusPending {
+ return ErrInvitationNotPending
+ }
+
+ if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusRevoked, s.now()); err != nil {
+ return ErrInvitationNotPending
+ }
+
+ s.emitAudit(ctx, &types.AuditLog{
+ TenantID: inv.TenantID,
+ ActorUserID: auditActor(ctx),
+ ActorRole: auditActorRole(ctx),
+ Action: types.AuditActionInvitationRevoked,
+ TargetType: "tenant_invitation",
+ TargetID: strconv.FormatUint(inv.ID, 10),
+ TargetUserID: inv.InviteeUserID,
+ Outcome: types.AuditOutcomeSuccess,
+ Details: detailsFor(inv.ID, inv.Role),
+ })
+ return nil
+}
+
+// GetByID returns the row or (nil, nil) without sweeping. The handler
+// uses this for narrow per-row checks where running a full sweep just
+// to read one row would be wasted work; List* paths still sweep.
+func (s *tenantInvitationService) GetByID(
+ ctx context.Context,
+ invID uint64,
+) (*types.TenantInvitation, error) {
+ return s.repo.GetByID(ctx, invID)
+}
+
+// ListByTenant sweeps then returns. The tenant-side management UI
+// expects expired rows to surface correctly; running the sweep here
+// guarantees the page reflects reality even if no other code path has
+// touched the table recently.
+func (s *tenantInvitationService) ListByTenant(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ s.sweep(ctx)
+ return s.repo.ListByTenant(ctx, tenantID, includeTerminal)
+}
+
+// ListTenantInvitationsPage sweeps then returns a page plus total rows
+// matching the same filter as ListByTenant.
+func (s *tenantInvitationService) ListTenantInvitationsPage(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+ page, pageSize int,
+) ([]*types.TenantInvitation, int64, error) {
+ const (
+ defSize = 20
+ maxSize = 100
+ )
+ s.sweep(ctx)
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = defSize
+ }
+ if pageSize > maxSize {
+ pageSize = maxSize
+ }
+ total, err := s.repo.CountByTenantList(ctx, tenantID, includeTerminal)
+ if err != nil {
+ return nil, 0, err
+ }
+ offset := (page - 1) * pageSize
+ rows, err := s.repo.ListByTenantPage(ctx, tenantID, includeTerminal, offset, pageSize)
+ if err != nil {
+ return nil, 0, err
+ }
+ return rows, total, nil
+}
+
+// ListByInvitee sweeps then returns. Same reasoning as ListByTenant.
+func (s *tenantInvitationService) ListByInvitee(
+ ctx context.Context,
+ inviteeUserID string,
+ includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ s.sweep(ctx)
+ return s.repo.ListByInvitee(ctx, inviteeUserID, includeTerminal)
+}
+
+// CountPendingByInvitee sweeps then counts. The avatar-row badge polls
+// this endpoint so a stale sweep would manifest as a phantom "1" on
+// the bell icon for the full polling interval; sweeping inline is
+// worth the extra UPDATE.
+func (s *tenantInvitationService) CountPendingByInvitee(
+ ctx context.Context,
+ inviteeUserID string,
+) (int64, error) {
+ s.sweep(ctx)
+ return s.repo.CountPendingByInvitee(ctx, inviteeUserID)
+}
diff --git a/internal/application/service/tenant_invitation_test.go b/internal/application/service/tenant_invitation_test.go
new file mode 100644
index 000000000..c2fa293ca
--- /dev/null
+++ b/internal/application/service/tenant_invitation_test.go
@@ -0,0 +1,397 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "sort"
+ "testing"
+ "time"
+
+ apprepo "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// fakeInvitationRepo is an in-memory stand-in for
+// interfaces.TenantInvitationRepository. The implementation is
+// deliberately tiny — these tests focus on the service-layer state
+// machine (Accept / Decline / Revoke / lazy sweep / duplicate guard)
+// rather than the SQL surface. The production repo gets exercised via
+// the real DB in repo tests if/when those are added.
+type fakeInvitationRepo struct {
+ rows []*types.TenantInvitation
+ nextID uint64
+}
+
+func newFakeInvitationRepo() *fakeInvitationRepo { return &fakeInvitationRepo{} }
+
+func (r *fakeInvitationRepo) Create(ctx context.Context, inv *types.TenantInvitation) error {
+ for _, e := range r.rows {
+ if e.TenantID == inv.TenantID &&
+ e.InviteeUserID == inv.InviteeUserID &&
+ e.Status == types.TenantInvitationStatusPending {
+ return apprepo.ErrPendingInvitationExists
+ }
+ }
+ r.nextID++
+ inv.ID = r.nextID
+ inv.CreatedAt = time.Now()
+ inv.UpdatedAt = inv.CreatedAt
+ cp := *inv
+ r.rows = append(r.rows, &cp)
+ return nil
+}
+
+func (r *fakeInvitationRepo) GetByID(ctx context.Context, id uint64) (*types.TenantInvitation, error) {
+ for _, e := range r.rows {
+ if e.ID == id {
+ cp := *e
+ return &cp, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *fakeInvitationRepo) GetPendingByPair(
+ ctx context.Context, tenantID uint64, inviteeUserID string,
+) (*types.TenantInvitation, error) {
+ for _, e := range r.rows {
+ if e.TenantID == tenantID &&
+ e.InviteeUserID == inviteeUserID &&
+ e.Status == types.TenantInvitationStatusPending {
+ cp := *e
+ return &cp, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *fakeInvitationRepo) filteredTenantRows(
+ tenantID uint64, includeTerminal bool,
+) []*types.TenantInvitation {
+ var out []*types.TenantInvitation
+ for _, e := range r.rows {
+ if e.TenantID != tenantID {
+ continue
+ }
+ if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
+ continue
+ }
+ cp := *e
+ out = append(out, &cp)
+ }
+ sort.SliceStable(out, func(i, j int) bool {
+ return out[i].ID > out[j].ID
+ })
+ return out
+}
+
+func (r *fakeInvitationRepo) ListByTenant(
+ ctx context.Context, tenantID uint64, includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ return r.filteredTenantRows(tenantID, includeTerminal), nil
+}
+
+func (r *fakeInvitationRepo) CountByTenantList(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+) (int64, error) {
+ return int64(len(r.filteredTenantRows(tenantID, includeTerminal))), nil
+}
+
+func (r *fakeInvitationRepo) ListByTenantPage(
+ ctx context.Context,
+ tenantID uint64,
+ includeTerminal bool,
+ offset, limit int,
+) ([]*types.TenantInvitation, error) {
+ all := r.filteredTenantRows(tenantID, includeTerminal)
+ if offset >= len(all) {
+ return []*types.TenantInvitation{}, nil
+ }
+ end := offset + limit
+ if end > len(all) {
+ end = len(all)
+ }
+ return append([]*types.TenantInvitation(nil), all[offset:end]...), nil
+}
+
+func (r *fakeInvitationRepo) ListByInvitee(
+ ctx context.Context, inviteeUserID string, includeTerminal bool,
+) ([]*types.TenantInvitation, error) {
+ var out []*types.TenantInvitation
+ for _, e := range r.rows {
+ if e.InviteeUserID != inviteeUserID {
+ continue
+ }
+ if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
+ continue
+ }
+ cp := *e
+ out = append(out, &cp)
+ }
+ return out, nil
+}
+
+func (r *fakeInvitationRepo) CountPendingByInvitee(
+ ctx context.Context, inviteeUserID string,
+) (int64, error) {
+ var n int64
+ for _, e := range r.rows {
+ if e.InviteeUserID == inviteeUserID &&
+ e.Status == types.TenantInvitationStatusPending {
+ n++
+ }
+ }
+ return n, nil
+}
+
+func (r *fakeInvitationRepo) MarkStatusIfPending(
+ ctx context.Context,
+ id uint64,
+ status types.TenantInvitationStatus,
+ respondedAt time.Time,
+) error {
+ for _, e := range r.rows {
+ if e.ID == id && e.Status == types.TenantInvitationStatusPending {
+ e.Status = status
+ e.RespondedAt = &respondedAt
+ e.UpdatedAt = time.Now()
+ return nil
+ }
+ }
+ return gormErrRecordNotFound
+}
+
+func (r *fakeInvitationRepo) SweepExpired(
+ ctx context.Context, now time.Time,
+) (int64, error) {
+ var n int64
+ for _, e := range r.rows {
+ if e.Status == types.TenantInvitationStatusPending && e.ExpiresAt.Before(now) {
+ e.Status = types.TenantInvitationStatusExpired
+ e.RespondedAt = &now
+ e.UpdatedAt = time.Now()
+ n++
+ }
+ }
+ return n, nil
+}
+
+var _ interfaces.TenantInvitationRepository = (*fakeInvitationRepo)(nil)
+
+// newInvitationSvc returns a service wired against in-memory fakes for
+// both the invitation repo and the member service. Audit is nil so
+// the lazy emitAudit short-circuit keeps the test surface focused.
+func newInvitationSvc() (
+ interfaces.TenantInvitationService,
+ *fakeInvitationRepo,
+ interfaces.TenantMemberService,
+) {
+ invRepo := newFakeInvitationRepo()
+ memberSvc, _ := newServiceWithRepo()
+ svc := NewTenantInvitationService(invRepo, memberSvc, nil)
+ return svc, invRepo, memberSvc
+}
+
+func TestInvitationService_Create_RejectsInvalidRole(t *testing.T) {
+ svc, _, _ := newInvitationSvc()
+ _, err := svc.Create(context.Background(), 1, "u-bob", types.TenantRole("magician"), nil, "")
+ if !errors.Is(err, ErrInvalidTenantRole) {
+ t.Fatalf("want ErrInvalidTenantRole, got %v", err)
+ }
+}
+
+func TestInvitationService_Create_RejectsAlreadyActiveMember(t *testing.T) {
+ svc, _, memberSvc := newInvitationSvc()
+ ctx := context.Background()
+ if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleContributor, nil); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
+ if !errors.Is(err, ErrAlreadyMember) {
+ t.Fatalf("want ErrAlreadyMember, got %v", err)
+ }
+}
+
+func TestInvitationService_Create_DedupsPending(t *testing.T) {
+ svc, _, _ := newInvitationSvc()
+ ctx := context.Background()
+ if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
+ t.Fatalf("first invite: %v", err)
+ }
+ _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
+ if !errors.Is(err, ErrPendingInvitationExists) {
+ t.Fatalf("want ErrPendingInvitationExists, got %v", err)
+ }
+}
+
+func TestInvitationService_Accept_OnlyByInvitee(t *testing.T) {
+ svc, _, _ := newInvitationSvc()
+ ctx := context.Background()
+ inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if _, err := svc.Accept(ctx, inv.ID, "u-eve"); !errors.Is(err, ErrInvitationForbidden) {
+ t.Fatalf("non-invitee must be forbidden, got %v", err)
+ }
+}
+
+func TestInvitationService_Accept_HappyPath_CreatesMembership(t *testing.T) {
+ svc, _, memberSvc := newInvitationSvc()
+ ctx := context.Background()
+ inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ mb, err := svc.Accept(ctx, inv.ID, "u-bob")
+ if err != nil {
+ t.Fatalf("accept: %v", err)
+ }
+ if mb == nil || mb.UserID != "u-bob" || mb.Role != types.TenantRoleAdmin {
+ t.Fatalf("unexpected membership: %+v", mb)
+ }
+ // Re-acceptance must be a state-machine rejection, not silent
+ // success — otherwise a duplicate click double-creates audit rows.
+ if _, err := svc.Accept(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
+ t.Fatalf("re-accept must reject as ErrInvitationNotPending, got %v", err)
+ }
+ // And the membership service must see the row exactly once.
+ got, _ := memberSvc.GetMembership(ctx, "u-bob", 1)
+ if got == nil {
+ t.Fatalf("membership row missing after accept")
+ }
+}
+
+func TestInvitationService_Accept_IdempotentWhenAlreadyMember(t *testing.T) {
+ // If the invitee somehow became an active member between Create
+ // and Accept (e.g. a parallel direct-add via POST /members), the
+ // Accept call must not 500 — it should fold gracefully into "you
+ // are already in" and flip the invitation to accepted for audit.
+ svc, invRepo, memberSvc := newInvitationSvc()
+ ctx := context.Background()
+ inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ // Side-effect: mint the membership directly.
+ if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleViewer, nil); err != nil {
+ t.Fatalf("side-effect AddMember: %v", err)
+ }
+ mb, err := svc.Accept(ctx, inv.ID, "u-bob")
+ if err != nil {
+ t.Fatalf("accept must be idempotent, got %v", err)
+ }
+ if mb == nil || mb.Role != types.TenantRoleViewer {
+ // Returns the pre-existing membership; the role on the
+ // invitation does NOT clobber a real membership row.
+ t.Fatalf("unexpected membership after idempotent accept: %+v", mb)
+ }
+ // Invitation row must reflect accepted state so the inbox no
+ // longer surfaces it as pending.
+ row, _ := invRepo.GetByID(ctx, inv.ID)
+ if row == nil || row.Status != types.TenantInvitationStatusAccepted {
+ t.Fatalf("invitation must be accepted after idempotent accept, got %+v", row)
+ }
+}
+
+func TestInvitationService_Decline_MarksDeclined(t *testing.T) {
+ svc, invRepo, _ := newInvitationSvc()
+ ctx := context.Background()
+ inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if err := svc.Decline(ctx, inv.ID, "u-bob"); err != nil {
+ t.Fatalf("decline: %v", err)
+ }
+ row, _ := invRepo.GetByID(ctx, inv.ID)
+ if row.Status != types.TenantInvitationStatusDeclined {
+ t.Fatalf("want declined status, got %s", row.Status)
+ }
+ if err := svc.Decline(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
+ t.Fatalf("double-decline must reject, got %v", err)
+ }
+}
+
+func TestInvitationService_Revoke_MarksRevoked(t *testing.T) {
+ svc, invRepo, _ := newInvitationSvc()
+ ctx := context.Background()
+ inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if err := svc.Revoke(ctx, inv.ID); err != nil {
+ t.Fatalf("revoke: %v", err)
+ }
+ row, _ := invRepo.GetByID(ctx, inv.ID)
+ if row.Status != types.TenantInvitationStatusRevoked {
+ t.Fatalf("want revoked status, got %s", row.Status)
+ }
+ // Revoked rows can be re-invited via a fresh Create — the
+ // partial unique index only guards PENDING.
+ if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
+ t.Fatalf("re-invite after revoke must succeed, got %v", err)
+ }
+}
+
+func TestInvitationService_LazySweepExpires(t *testing.T) {
+ // Drop a row directly into the repo with an ExpiresAt in the past,
+ // then call ListByInvitee — the sweep must flip it to expired
+ // before the read returns.
+ svc, invRepo, _ := newInvitationSvc()
+ now := time.Now()
+ stale := &types.TenantInvitation{
+ TenantID: 1,
+ InviteeUserID: "u-bob",
+ Role: types.TenantRoleViewer,
+ Status: types.TenantInvitationStatusPending,
+ ExpiresAt: now.Add(-time.Hour),
+ }
+ if err := invRepo.Create(context.Background(), stale); err != nil {
+ t.Fatalf("seed stale: %v", err)
+ }
+
+ rows, err := svc.ListByInvitee(context.Background(), "u-bob", true)
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if len(rows) != 1 || rows[0].Status != types.TenantInvitationStatusExpired {
+ t.Fatalf("expected expired row after sweep, got %+v", rows)
+ }
+
+ // And accepting an expired invitation must fail loudly rather than
+ // quietly creating the membership.
+ if _, err := svc.Accept(context.Background(), stale.ID, "u-bob"); err == nil {
+ t.Fatalf("accept on expired invitation must fail")
+ }
+}
+
+func TestInvitationService_CountPending(t *testing.T) {
+ svc, _, _ := newInvitationSvc()
+ ctx := context.Background()
+ if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, ""); err != nil {
+ t.Fatalf("seed1: %v", err)
+ }
+ if _, err := svc.Create(ctx, 2, "u-bob", types.TenantRoleAdmin, nil, ""); err != nil {
+ t.Fatalf("seed2: %v", err)
+ }
+ n, err := svc.CountPendingByInvitee(ctx, "u-bob")
+ if err != nil {
+ t.Fatalf("count: %v", err)
+ }
+ if n != 2 {
+ t.Fatalf("want 2 pending, got %d", n)
+ }
+ // Decline one; count drops.
+ rows, _ := svc.ListByInvitee(ctx, "u-bob", false)
+ if err := svc.Decline(ctx, rows[0].ID, "u-bob"); err != nil {
+ t.Fatalf("decline: %v", err)
+ }
+ n, _ = svc.CountPendingByInvitee(ctx, "u-bob")
+ if n != 1 {
+ t.Fatalf("want 1 pending after decline, got %d", n)
+ }
+}
diff --git a/internal/application/service/tenant_member.go b/internal/application/service/tenant_member.go
index 0a9b02040..97a721543 100644
--- a/internal/application/service/tenant_member.go
+++ b/internal/application/service/tenant_member.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "strings"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
@@ -33,6 +34,11 @@ var (
ErrLastOwner = errors.New("cannot demote or remove the last active owner of the tenant")
)
+const (
+ listMembersDefaultPageSize = 20
+ listMembersMaxPageSize = 100
+)
+
// tenantMemberService implements interfaces.TenantMemberService.
type tenantMemberService struct {
repo interfaces.TenantMemberRepository
@@ -172,6 +178,36 @@ func (s *tenantMemberService) ListByTenant(ctx context.Context, tenantID uint64)
return s.repo.ListByTenant(ctx, tenantID)
}
+// ListMembersPage returns a slice plus total matching query (handlers parse
+// page/page_size; defensive clamps here mirror list handler limits).
+func (s *tenantMemberService) ListMembersPage(
+ ctx context.Context,
+ tenantID uint64,
+ query string,
+ page, pageSize int,
+) ([]*types.TenantMember, int64, error) {
+ query = strings.TrimSpace(query)
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = listMembersDefaultPageSize
+ }
+ if pageSize > listMembersMaxPageSize {
+ pageSize = listMembersMaxPageSize
+ }
+ total, err := s.repo.CountFilteredByTenant(ctx, tenantID, query)
+ if err != nil {
+ return nil, 0, err
+ }
+ offset := (page - 1) * pageSize
+ members, err := s.repo.ListPagedByTenant(ctx, tenantID, query, offset, pageSize)
+ if err != nil {
+ return nil, 0, err
+ }
+ return members, total, nil
+}
+
// HasAnyMembers proxies to the repository.
func (s *tenantMemberService) HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error) {
return s.repo.HasAnyMembers(ctx, tenantID)
diff --git a/internal/application/service/tenant_member_test.go b/internal/application/service/tenant_member_test.go
index 2bd7cd9d1..20532102d 100644
--- a/internal/application/service/tenant_member_test.go
+++ b/internal/application/service/tenant_member_test.go
@@ -3,6 +3,8 @@ package service
import (
"context"
"errors"
+ "sort"
+ "strings"
"testing"
"time"
@@ -90,6 +92,50 @@ func (r *fakeTenantMemberRepo) ListByTenant(ctx context.Context, tenantID uint64
return out, nil
}
+func (r *fakeTenantMemberRepo) filterTenantRows(tenantID uint64, search string) []*types.TenantMember {
+ search = strings.TrimSpace(strings.ToLower(search))
+ var out []*types.TenantMember
+ for _, e := range r.rows {
+ if e.TenantID != tenantID || e.DeletedAt.Valid {
+ continue
+ }
+ if search != "" {
+ if !strings.Contains(strings.ToLower(e.UserID), search) {
+ continue
+ }
+ }
+ cp := *e
+ out = append(out, &cp)
+ }
+ sort.SliceStable(out, func(i, j int) bool {
+ if out[i].JoinedAt.Equal(out[j].JoinedAt) {
+ return out[i].ID < out[j].ID
+ }
+ return out[i].JoinedAt.Before(out[j].JoinedAt)
+ })
+ return out
+}
+
+func (r *fakeTenantMemberRepo) CountFilteredByTenant(
+ ctx context.Context, tenantID uint64, search string,
+) (int64, error) {
+ return int64(len(r.filterTenantRows(tenantID, search))), nil
+}
+
+func (r *fakeTenantMemberRepo) ListPagedByTenant(
+ ctx context.Context, tenantID uint64, search string, offset, limit int,
+) ([]*types.TenantMember, error) {
+ all := r.filterTenantRows(tenantID, search)
+ if offset >= len(all) {
+ return []*types.TenantMember{}, nil
+ }
+ end := offset + limit
+ if end > len(all) {
+ end = len(all)
+ }
+ return append([]*types.TenantMember(nil), all[offset:end]...), nil
+}
+
func (r *fakeTenantMemberRepo) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
if r.failUpdateRole != nil {
return r.failUpdateRole
diff --git a/internal/container/container.go b/internal/container/container.go
index f6a99b7f3..78be5f905 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -136,6 +136,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering repositories...")
must(container.Provide(repository.NewTenantRepository))
must(container.Provide(repository.NewTenantMemberRepository))
+ must(container.Provide(repository.NewTenantInvitationRepository))
must(container.Provide(repository.NewAuditLogRepository))
must(container.Provide(repository.NewKnowledgeBaseRepository))
must(container.Provide(repository.NewKnowledgeRepository))
@@ -172,6 +173,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering business services...")
must(container.Provide(service.NewTenantService))
must(container.Provide(service.NewTenantMemberService))
+ must(container.Provide(service.NewTenantInvitationService))
must(container.Provide(service.NewAuditLogService))
must(container.Provide(service.NewAuditLogRetentionRunner))
must(container.Provide(service.NewKnowledgeBaseService))
@@ -290,6 +292,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering HTTP handlers...")
must(container.Provide(handler.NewTenantHandler))
must(container.Provide(handler.NewTenantMemberHandler))
+ must(container.Provide(handler.NewTenantInvitationHandler))
must(container.Provide(handler.NewAuditLogHandler))
must(container.Provide(handler.NewKnowledgeBaseHandler))
must(container.Provide(handler.NewKnowledgeHandler))
diff --git a/internal/handler/list_pagination.go b/internal/handler/list_pagination.go
new file mode 100644
index 000000000..d574b7447
--- /dev/null
+++ b/internal/handler/list_pagination.go
@@ -0,0 +1,42 @@
+package handler
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+)
+
+const (
+ defaultListPageSize = 20
+ maxListPageSize = 100
+)
+
+// parseListPagination parses ?page and ?page_size for tenant-scoped list
+// endpoints. Omitted keys default to page=1 and page_size=20. A present but
+// malformed or out-of-range value yields a validation error on the context.
+func parseListPagination(c *gin.Context) (page, pageSize int, ok bool) {
+ page = 1
+ pageSize = defaultListPageSize
+
+ if s := strings.TrimSpace(c.Query("page")); s != "" {
+ p, err := strconv.Atoi(s)
+ if err != nil || p < 1 {
+ c.Error(apperrors.NewValidationError("page must be a positive integer"))
+ return 0, 0, false
+ }
+ page = p
+ }
+ if s := strings.TrimSpace(c.Query("page_size")); s != "" {
+ ps, err := strconv.Atoi(s)
+ if err != nil || ps < 1 || ps > maxListPageSize {
+ c.Error(apperrors.NewValidationError(fmt.Sprintf("page_size must be between 1 and %d", maxListPageSize)))
+ return 0, 0, false
+ }
+ pageSize = ps
+ }
+ return page, pageSize, true
+}
diff --git a/internal/handler/tenant_invitation.go b/internal/handler/tenant_invitation.go
new file mode 100644
index 000000000..ca3ddd2b0
--- /dev/null
+++ b/internal/handler/tenant_invitation.go
@@ -0,0 +1,506 @@
+package handler
+
+import (
+ "errors"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+
+ apprepo "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+)
+
+// TenantInvitationHandler exposes the tenant-scoped CRUD on the
+// `tenant_invitations` table plus the user-self-service inbox endpoints
+// (/me/invitations*). Route-level RBAC: tenant routes are Owner-gated
+// (POST/DELETE) or Viewer-gated (GET); inbox routes only require
+// authentication (the service enforces "only invitee can act").
+type TenantInvitationHandler struct {
+ invitationService interfaces.TenantInvitationService
+ userService interfaces.UserService
+ tenantService interfaces.TenantService
+}
+
+// NewTenantInvitationHandler wires the dependencies. tenantService is
+// used to hydrate tenant names in the inbox view so the invitee sees
+// "join Foo Workspace" instead of a raw numeric tenant id.
+func NewTenantInvitationHandler(
+ invitationService interfaces.TenantInvitationService,
+ userService interfaces.UserService,
+ tenantService interfaces.TenantService,
+) *TenantInvitationHandler {
+ return &TenantInvitationHandler{
+ invitationService: invitationService,
+ userService: userService,
+ tenantService: tenantService,
+ }
+}
+
+// createInvitationRequest is the JSON body for POST /tenants/:id/invitations.
+// Email is the user-facing identifier; the handler resolves it to a
+// User row before delegating to the service. The optional Message is
+// surfaced in the invitee's inbox.
+type createInvitationRequest struct {
+ Email string `json:"email" binding:"required,email"`
+ Role types.TenantRole `json:"role" binding:"required"`
+ Message string `json:"message"`
+}
+
+// parseInvitationIDFromPath reads :inv_id off the gin context.
+func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
+ raw := strings.TrimSpace(c.Param("inv_id"))
+ if raw == "" {
+ c.Error(apperrors.NewValidationError("invitation id is required"))
+ return 0, false
+ }
+ v, err := strconv.ParseUint(raw, 10, 64)
+ if err != nil || v == 0 {
+ c.Error(apperrors.NewValidationError("invitation id must be a positive integer"))
+ return 0, false
+ }
+ return v, true
+}
+
+// projectInvitation hydrates a single TenantInvitation row into the
+// API response shape. Inviter / invitee user fields and the tenant
+// name are filled best-effort: a missing row degrades to the bare id
+// rather than dropping the response. usersByID and tenantsByID let the
+// caller batch the lookups when projecting a list.
+func projectInvitation(
+ inv *types.TenantInvitation,
+ usersByID map[string]*types.User,
+ tenantsByID map[uint64]*types.Tenant,
+) types.TenantInvitationResponse {
+ resp := types.TenantInvitationResponse{
+ ID: inv.ID,
+ TenantID: inv.TenantID,
+ InviteeUserID: inv.InviteeUserID,
+ InvitedBy: inv.InvitedBy,
+ Role: inv.Role,
+ Status: inv.Status,
+ Message: inv.Message,
+ ExpiresAt: inv.ExpiresAt,
+ RespondedAt: inv.RespondedAt,
+ CreatedAt: inv.CreatedAt,
+ }
+ if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
+ resp.InviteeEmail = u.Email
+ resp.InviteeName = u.Username
+ }
+ if inv.InvitedBy != nil {
+ if u, ok := usersByID[*inv.InvitedBy]; ok && u != nil {
+ resp.InviterEmail = u.Email
+ resp.InviterName = u.Username
+ }
+ }
+ if t, ok := tenantsByID[inv.TenantID]; ok && t != nil {
+ resp.TenantName = t.Name
+ }
+ return resp
+}
+
+// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
+// Best-effort: a transient lookup failure logs and returns an empty
+// map so the projection falls back to ids.
+func (h *TenantInvitationHandler) hydrateUsers(c *gin.Context, invs []*types.TenantInvitation) map[string]*types.User {
+ if len(invs) == 0 {
+ return map[string]*types.User{}
+ }
+ idSet := make(map[string]struct{}, len(invs)*2)
+ for _, inv := range invs {
+ idSet[inv.InviteeUserID] = struct{}{}
+ if inv.InvitedBy != nil {
+ idSet[*inv.InvitedBy] = struct{}{}
+ }
+ }
+ ids := make([]string, 0, len(idSet))
+ for id := range idSet {
+ ids = append(ids, id)
+ }
+ users, err := h.userService.GetUsersByIDs(c.Request.Context(), ids)
+ if err != nil {
+ logger.Warnf(c.Request.Context(), "invitation list: batch user hydrate failed: %v", err)
+ return map[string]*types.User{}
+ }
+ return users
+}
+
+// hydrateTenants is the same idea over the distinct tenant_ids touched
+// by `invs`. Used by the /me inbox view where invitations span tenants.
+func (h *TenantInvitationHandler) hydrateTenants(c *gin.Context, invs []*types.TenantInvitation) map[uint64]*types.Tenant {
+ if len(invs) == 0 || h.tenantService == nil {
+ return map[uint64]*types.Tenant{}
+ }
+ idSet := make(map[uint64]struct{}, len(invs))
+ for _, inv := range invs {
+ idSet[inv.TenantID] = struct{}{}
+ }
+ ids := make([]uint64, 0, len(idSet))
+ for id := range idSet {
+ ids = append(ids, id)
+ }
+ tenants, err := h.tenantService.GetTenantsByIDs(c.Request.Context(), ids)
+ if err != nil {
+ logger.Warnf(c.Request.Context(), "invitation list: batch tenant hydrate failed: %v", err)
+ return map[uint64]*types.Tenant{}
+ }
+ return tenants
+}
+
+// ListTenantInvitations godoc
+// @Summary 列出租户邀请
+// @Description 按 tenant 列出待接受 / 历史邀请。query include_terminal=true 时附带 accepted/declined/revoked/expired。
+// @Tags 租户邀请
+// @Produce json
+// @Param id path string true "租户 ID"
+// @Param include_terminal query bool false "是否包含终止态行(默认 false)"
+// @Param page query int false "页码(从 1 起)" default(1)
+// @Param page_size query int false "每页数量" default(20)
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /tenants/{id}/invitations [get]
+func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
+ ctx := c.Request.Context()
+ tenantID, ok := parseTenantIDFromPath(c)
+ if !ok {
+ return
+ }
+ includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
+
+ page, pageSize, ok := parseListPagination(c)
+ if !ok {
+ return
+ }
+
+ rows, total, err := h.invitationService.ListTenantInvitationsPage(ctx, tenantID, includeTerminal, page, pageSize)
+ if err != nil {
+ logger.Errorf(ctx, "ListTenantInvitationsPage failed: tenant=%d err=%v", tenantID, err)
+ c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
+ return
+ }
+
+ usersByID := h.hydrateUsers(c, rows)
+ resp := make([]types.TenantInvitationResponse, 0, len(rows))
+ for _, inv := range rows {
+ // Within the tenant view we don't bother hydrating tenant name
+ // (the caller already knows the tenant). Pass an empty map.
+ resp = append(resp, projectInvitation(inv, usersByID, nil))
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "invitations": resp,
+ "total": total,
+ "page": page,
+ "page_size": pageSize,
+ },
+ })
+}
+
+// CreateInvitation godoc
+// @Summary 发出租户邀请
+// @Description Owner 通过邮箱邀请已注册用户加入当前租户;被邀请人需要在 /me/invitations 接受后才会成为成员。
+// @Tags 租户邀请
+// @Accept json
+// @Produce json
+// @Param id path string true "租户 ID"
+// @Param request body createInvitationRequest true "邀请请求"
+// @Success 201 {object} map[string]interface{}
+// @Security Bearer
+// @Router /tenants/{id}/invitations [post]
+func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {
+ ctx := c.Request.Context()
+ tenantID, ok := parseTenantIDFromPath(c)
+ if !ok {
+ return
+ }
+
+ var req createInvitationRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
+ return
+ }
+ if !req.Role.IsValid() {
+ c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
+ return
+ }
+
+ user, err := h.userService.GetUserByEmail(ctx, strings.TrimSpace(req.Email))
+ if err != nil {
+ if errors.Is(err, apprepo.ErrUserNotFound) {
+ c.Error(apperrors.NewNotFoundError(
+ "user with this email is not registered; ask them to sign up first"))
+ return
+ }
+ logger.Errorf(ctx, "GetUserByEmail failed: email=%s err=%v",
+ secutils.SanitizeForLog(req.Email), err)
+ c.Error(apperrors.NewInternalServerError("failed to look up user").WithDetails(err.Error()))
+ return
+ }
+
+ caller, _ := types.UserIDFromContext(ctx)
+ var invitedBy *string
+ if caller != "" && !types.IsSyntheticUserID(caller) {
+ invitedBy = &caller
+ }
+
+ inv, err := h.invitationService.Create(ctx, tenantID, user.ID, req.Role, invitedBy, req.Message)
+ if err != nil {
+ switch {
+ case errors.Is(err, service.ErrInvalidTenantRole):
+ c.Error(apperrors.NewValidationError(err.Error()))
+ case errors.Is(err, service.ErrPendingInvitationExists):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ case errors.Is(err, service.ErrAlreadyMember):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ default:
+ logger.Errorf(ctx, "CreateInvitation failed: user=%s tenant=%d err=%v",
+ user.ID, tenantID, err)
+ c.Error(apperrors.NewInternalServerError("failed to create invitation").WithDetails(err.Error()))
+ }
+ return
+ }
+
+ usersByID := map[string]*types.User{user.ID: user}
+ if invitedBy != nil {
+ // Best-effort hydrate inviter too. Errors are swallowed —
+ // the response degrades to just the invitee fields.
+ if u, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && u != nil {
+ usersByID[u.ID] = u
+ }
+ }
+ resp := projectInvitation(inv, usersByID, nil)
+ c.JSON(http.StatusCreated, gin.H{
+ "success": true,
+ "data": resp,
+ })
+}
+
+// RevokeInvitation godoc
+// @Summary 撤销待接受邀请
+// @Description Owner 取消一条还在 pending 的邀请;已 accepted/declined/revoked/expired 的行不可再撤销。
+// @Tags 租户邀请
+// @Produce json
+// @Param id path string true "租户 ID"
+// @Param inv_id path string true "邀请 ID"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /tenants/{id}/invitations/{inv_id} [delete]
+func (h *TenantInvitationHandler) RevokeInvitation(c *gin.Context) {
+ ctx := c.Request.Context()
+ tenantID, ok := parseTenantIDFromPath(c)
+ if !ok {
+ return
+ }
+ invID, ok := parseInvitationIDFromPath(c)
+ if !ok {
+ return
+ }
+
+ // Cross-check the invitation lives in the URL :id. The route layer
+ // already verifies the caller has Owner on the active tenant AND
+ // the URL :id matches the active tenant (PathTenantMatch), but the
+ // invitation row itself carries its own tenant_id we have to honour
+ // — otherwise an Owner of A could revoke invitations of B by URL-
+ // crafting against /tenants/A/invitations/<inv-of-B>.
+ inv, err := h.invitationService.GetByID(ctx, invID)
+ if err != nil {
+ logger.Errorf(ctx, "GetByID invitation failed: id=%d err=%v", invID, err)
+ c.Error(apperrors.NewInternalServerError("failed to load invitation").WithDetails(err.Error()))
+ return
+ }
+ if inv == nil {
+ c.Error(apperrors.NewNotFoundError("invitation not found"))
+ return
+ }
+ if inv.TenantID != tenantID {
+ // Render the same 404 as "missing" so we don't leak existence
+ // across tenants.
+ c.Error(apperrors.NewNotFoundError("invitation not found"))
+ return
+ }
+
+ if err := h.invitationService.Revoke(ctx, invID); err != nil {
+ switch {
+ case errors.Is(err, service.ErrInvitationNotFound):
+ c.Error(apperrors.NewNotFoundError("invitation not found"))
+ case errors.Is(err, service.ErrInvitationNotPending):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ default:
+ logger.Errorf(ctx, "RevokeInvitation failed: id=%d err=%v", invID, err)
+ c.Error(apperrors.NewInternalServerError("failed to revoke invitation").WithDetails(err.Error()))
+ }
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// ListMyInvitations godoc
+// @Summary 列出我的待接受邀请
+// @Description 返回当前登录用户的待接受邀请(默认仅 pending),用于头像入口和 /invitations 收件箱页。
+// @Tags 我的邀请
+// @Produce json
+// @Param include_terminal query bool false "是否包含已处理 / 已过期等终止态行(默认 false)"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /me/invitations [get]
+func (h *TenantInvitationHandler) ListMyInvitations(c *gin.Context) {
+ ctx := c.Request.Context()
+ caller, ok := types.UserIDFromContext(ctx)
+ if !ok || caller == "" {
+ c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
+ return
+ }
+ includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
+
+ rows, err := h.invitationService.ListByInvitee(ctx, caller, includeTerminal)
+ if err != nil {
+ logger.Errorf(ctx, "ListByInvitee invitations failed: user=%s err=%v", caller, err)
+ c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
+ return
+ }
+
+ usersByID := h.hydrateUsers(c, rows)
+ tenantsByID := h.hydrateTenants(c, rows)
+ resp := make([]types.TenantInvitationResponse, 0, len(rows))
+ for _, inv := range rows {
+ resp = append(resp, projectInvitation(inv, usersByID, tenantsByID))
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "invitations": resp,
+ "total": len(resp),
+ },
+ })
+}
+
+// CountMyPendingInvitations godoc
+// @Summary 获取我的待处理邀请数
+// @Description 轻量级 endpoint,返回当前登录用户的 pending 邀请数,用于头像旁的角标轮询。
+// @Tags 我的邀请
+// @Produce json
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /me/invitations/pending-count [get]
+func (h *TenantInvitationHandler) CountMyPendingInvitations(c *gin.Context) {
+ ctx := c.Request.Context()
+ caller, ok := types.UserIDFromContext(ctx)
+ if !ok || caller == "" {
+ c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
+ return
+ }
+
+ count, err := h.invitationService.CountPendingByInvitee(ctx, caller)
+ if err != nil {
+ logger.Errorf(ctx, "CountPendingByInvitee failed: user=%s err=%v", caller, err)
+ c.Error(apperrors.NewInternalServerError("failed to count pending invitations").WithDetails(err.Error()))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{"pending_count": count},
+ })
+}
+
+// AcceptMyInvitation godoc
+// @Summary 接受邀请
+// @Description 当前登录用户接受一条 pending 邀请;服务端会同时写入 tenant_members 行。
+// @Tags 我的邀请
+// @Produce json
+// @Param inv_id path string true "邀请 ID"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /me/invitations/{inv_id}/accept [post]
+func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
+ ctx := c.Request.Context()
+ caller, ok := types.UserIDFromContext(ctx)
+ if !ok || caller == "" {
+ c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
+ return
+ }
+ invID, ok := parseInvitationIDFromPath(c)
+ if !ok {
+ return
+ }
+
+ member, err := h.invitationService.Accept(ctx, invID, caller)
+ if err != nil {
+ switch {
+ case errors.Is(err, service.ErrInvitationNotFound):
+ c.Error(apperrors.NewNotFoundError("invitation not found"))
+ case errors.Is(err, service.ErrInvitationForbidden):
+ c.Error(apperrors.NewForbiddenError(err.Error()))
+ case errors.Is(err, service.ErrInvitationNotPending):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ case errors.Is(err, service.ErrInvitationExpired):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ default:
+ logger.Errorf(ctx, "AcceptMyInvitation failed: id=%d user=%s err=%v",
+ invID, caller, err)
+ c.Error(apperrors.NewInternalServerError("failed to accept invitation").WithDetails(err.Error()))
+ }
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "membership": gin.H{
+ "tenant_id": member.TenantID,
+ "role": member.Role,
+ "status": member.Status,
+ "joined_at": member.JoinedAt,
+ },
+ },
+ })
+}
+
+// DeclineMyInvitation godoc
+// @Summary 拒绝邀请
+// @Description 当前登录用户拒绝一条 pending 邀请;不创建 tenant_members 行。
+// @Tags 我的邀请
+// @Produce json
+// @Param inv_id path string true "邀请 ID"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /me/invitations/{inv_id}/decline [post]
+func (h *TenantInvitationHandler) DeclineMyInvitation(c *gin.Context) {
+ ctx := c.Request.Context()
+ caller, ok := types.UserIDFromContext(ctx)
+ if !ok || caller == "" {
+ c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
+ return
+ }
+ invID, ok := parseInvitationIDFromPath(c)
+ if !ok {
+ return
+ }
+
+ if err := h.invitationService.Decline(ctx, invID, caller); err != nil {
+ switch {
+ case errors.Is(err, service.ErrInvitationNotFound):
+ c.Error(apperrors.NewNotFoundError("invitation not found"))
+ case errors.Is(err, service.ErrInvitationForbidden):
+ c.Error(apperrors.NewForbiddenError(err.Error()))
+ case errors.Is(err, service.ErrInvitationNotPending):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ case errors.Is(err, service.ErrInvitationExpired):
+ c.Error(apperrors.NewConflictError(err.Error()))
+ default:
+ logger.Errorf(ctx, "DeclineMyInvitation failed: id=%d user=%s err=%v",
+ invID, caller, err)
+ c.Error(apperrors.NewInternalServerError("failed to decline invitation").WithDetails(err.Error()))
+ }
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
diff --git a/internal/handler/tenant_member.go b/internal/handler/tenant_member.go
index 0bc1e25f3..b46e172a6 100644
--- a/internal/handler/tenant_member.go
+++ b/internal/handler/tenant_member.go
@@ -86,10 +86,13 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
// ListMembers godoc
// @Summary 列出租户成员
-// @Description 返回当前租户内全部 active 成员(含每位成员的角色、邮箱、头像)
+// @Description 分页返回当前租户内 active 成员(含每位成员的角色、邮箱、头像);支持 q 按邮箱/用户名筛选
// @Tags 租户成员
// @Produce json
-// @Param id path string true "租户 ID"
+// @Param id path string true "租户 ID"
+// @Param q query string false "按邮箱/用户名模糊筛选"
+// @Param page query int false "页码(从 1 起)" default(1)
+// @Param page_size query int false "每页数量(最大 100)" default(20)
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/members [get]
@@ -100,9 +103,15 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
return
}
- members, err := h.memberService.ListByTenant(ctx, tenantID)
+ q := strings.TrimSpace(c.Query("q"))
+ page, pageSize, ok := parseListPagination(c)
+ if !ok {
+ return
+ }
+
+ members, total, err := h.memberService.ListMembersPage(ctx, tenantID, q, page, pageSize)
if err != nil {
- logger.Errorf(ctx, "ListByTenant failed: tenant=%d err=%v", tenantID, err)
+ logger.Errorf(ctx, "ListMembersPage failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to list members").WithDetails(err.Error()))
return
}
@@ -144,15 +153,31 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
- "members": resp,
- "total": len(resp),
+ "members": resp,
+ "total": total,
+ "page": page,
+ "page_size": pageSize,
},
})
}
// AddMember godoc
-// @Summary 添加租户成员
-// @Description Owner 通过 email 邀请已经存在的用户加入当前租户
+// @Summary 直接添加租户成员(直加路径)
+// @Description
+//
+// Owner 通过 email 直接把用户作为 active 成员添加进当前租户。
+//
+// 这是【直加路径】,被加入的用户没有任何确认机会就出现在租户里——
+// 保留它是为了三类不需要走邀请确认的场景:
+// 1. 自动化脚本 / 平台运维 / 数据迁移;
+// 2. 跨租户超管 (CanAccessAllTenants) 的批量编排;
+// 3. 对接外部 IdP 时由身份源单向同步成员。
+//
+// 所有由 UI 触发的「邀请伙伴加入」交互应改走
+// POST /tenants/:id/invitations,那条路径会先创建 pending 行,让被邀请
+// 人在 /me/invitations 主动接受后再写 tenant_members 行(PR #1303 后续)。
+// 这条路径与 invitations 路径共存而不互相替代。
+//
// @Tags 租户成员
// @Accept json
// @Produce json
diff --git a/internal/handler/tenant_member_test.go b/internal/handler/tenant_member_test.go
index 753242543..cd94f2b32 100644
--- a/internal/handler/tenant_member_test.go
+++ b/internal/handler/tenant_member_test.go
@@ -26,10 +26,46 @@ import (
// gotten here" assertions.
type stubMemberService struct {
interfaces.TenantMemberService
- add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
- listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
- updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
- remove func(ctx context.Context, userID string, tenantID uint64) error
+ add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
+ listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
+ listMembersPage func(ctx context.Context, tenantID uint64, query string, page, pageSize int) ([]*types.TenantMember, int64, error)
+ updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
+ remove func(ctx context.Context, userID string, tenantID uint64) error
+}
+
+func (s *stubMemberService) ListMembersPage(
+ ctx context.Context,
+ tenantID uint64,
+ query string,
+ page, pageSize int,
+) ([]*types.TenantMember, int64, error) {
+ if s.listMembersPage != nil {
+ return s.listMembersPage(ctx, tenantID, query, page, pageSize)
+ }
+ if s.listTenant != nil {
+ members, err := s.listTenant(ctx, tenantID)
+ if err != nil {
+ return nil, 0, err
+ }
+ total := int64(len(members))
+ if page < 1 {
+ page = 1
+ }
+ if pageSize < 1 {
+ pageSize = 20
+ }
+ off := (page - 1) * pageSize
+ if off >= len(members) {
+ return []*types.TenantMember{}, total, nil
+ }
+ end := off + pageSize
+ if end > len(members) {
+ end = len(members)
+ }
+ slice := append([]*types.TenantMember(nil), members[off:end]...)
+ return slice, total, nil
+ }
+ return []*types.TenantMember{}, 0, nil
}
func (s *stubMemberService) AddMember(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error) {
@@ -260,6 +296,14 @@ func TestTenantMember_ListMembers_RejectsBadTenantID(t *testing.T) {
}
}
+func TestTenantMember_ListMembers_RejectsInvalidPage(t *testing.T) {
+ h := newTestMemberHandler(&stubMemberService{}, &stubMemberUserService{})
+ w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members?page=0", nil, "u1")
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("page=0 must 400, got %d body=%s", w.Code, w.Body.String())
+ }
+}
+
// ---------- AddMember ----------
func TestTenantMember_AddMember_HappyPath(t *testing.T) {
diff --git a/internal/middleware/auth_role_test.go b/internal/middleware/auth_role_test.go
index f5a38121d..53a04df07 100644
--- a/internal/middleware/auth_role_test.go
+++ b/internal/middleware/auth_role_test.go
@@ -107,6 +107,11 @@ func (f *fakeMemberService) ListByUser(ctx context.Context, userID string) ([]*t
func (f *fakeMemberService) ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error) {
return nil, nil
}
+func (f *fakeMemberService) ListMembersPage(
+ ctx context.Context, tenantID uint64, query string, page, pageSize int,
+) ([]*types.TenantMember, int64, error) {
+ return nil, 0, nil
+}
func (f *fakeMemberService) HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error) {
if f.failHasAny != nil {
return false, f.failHasAny
diff --git a/internal/router/router.go b/internal/router/router.go
index 3b6041f55..a0648ddf4 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -52,6 +52,7 @@ type RouterParams struct {
TenantService interfaces.TenantService
TenantMemberService interfaces.TenantMemberService
TenantMemberHandler *handler.TenantMemberHandler
+ TenantInvitationHandler *handler.TenantInvitationHandler
AuditLogHandler *handler.AuditLogHandler
AuditLogService interfaces.AuditLogService
ChunkHandler *handler.ChunkHandler
@@ -174,7 +175,8 @@ func NewRouter(params RouterParams) *gin.Engine {
)
RegisterAuthRoutes(v1, params.AuthHandler)
- RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.AuditLogHandler, rbacGuards)
+ RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.TenantInvitationHandler, params.AuditLogHandler, rbacGuards)
+ RegisterMyInvitationRoutes(v1, params.TenantInvitationHandler)
RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards)
RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards)
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards)
@@ -487,6 +489,7 @@ func RegisterTenantRoutes(
r *gin.RouterGroup,
handler *handler.TenantHandler,
memberHandler *handler.TenantMemberHandler,
+ invitationHandler *handler.TenantInvitationHandler,
auditLogHandler *handler.AuditLogHandler,
g *rbacGuards,
) {
@@ -537,6 +540,21 @@ func RegisterTenantRoutes(
tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant)
}
+ // Tenant invitation flow. The UI-driven "Invite Member"
+ // button hits POST /invitations rather than POST /members,
+ // so the invitee gets to confirm via /me/invitations
+ // before any tenant_members row is written. List is
+ // Viewer+ so any member can see pending invites in the
+ // management view; create/revoke are Owner+ to match the
+ // existing /members mutation gates. nil-skip pattern
+ // mirrors memberHandler above for environments built
+ // without the invitation dependency wired.
+ if invitationHandler != nil {
+ tenantByID.GET("/invitations", g.Viewer(), invitationHandler.ListTenantInvitations)
+ tenantByID.POST("/invitations", g.Owner(), invitationHandler.CreateInvitation)
+ tenantByID.DELETE("/invitations/:inv_id", g.Owner(), invitationHandler.RevokeInvitation)
+ }
+
// Audit log feed (PR 6 of #1303). Admin+ so denied-action
// histories don't surface to ordinary members; the
// PathTenantMatch group already prevents cross-tenant
@@ -592,6 +610,32 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
}
}
+// RegisterMyInvitationRoutes wires the per-user invitation inbox under
+// /me/invitations. The v1 group already applies middleware.Auth so we
+// don't need a role gate here — the service enforces "only the invitee
+// can accept/decline". The list endpoint mounts under /me to make the
+// "show me MY invitations" semantics obvious in URLs and logs (vs the
+// tenant-scoped /tenants/:id/invitations which lists ALL invitations
+// for the tenant). pending-count is a separate, ultra-light endpoint
+// the avatar-row badge polls; splitting it off so polling doesn't
+// transfer the full list every cycle.
+//
+// invitationHandler may be nil in environments built without the
+// invitation dependency wired; that's a no-op registration which is
+// preferable to a startup crash.
+func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.TenantInvitationHandler) {
+ if invitationHandler == nil {
+ return
+ }
+ me := r.Group("/me")
+ {
+ me.GET("/invitations", invitationHandler.ListMyInvitations)
+ me.GET("/invitations/pending-count", invitationHandler.CountMyPendingInvitations)
+ me.POST("/invitations/:inv_id/accept", invitationHandler.AcceptMyInvitation)
+ me.POST("/invitations/:inv_id/decline", invitationHandler.DeclineMyInvitation)
+ }
+}
+
// RegisterAuthRoutes registers authentication routes
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/register", handler.Register)
diff --git a/internal/types/audit_log.go b/internal/types/audit_log.go
index d909717fd..4432e7f76 100644
--- a/internal/types/audit_log.go
+++ b/internal/types/audit_log.go
@@ -30,6 +30,26 @@ const (
// EnableRBAC=true. Subject to 1-minute sliding-window dedup so a
// probing client cannot fill the table.
AuditActionAccessDenied AuditAction = "rbac.access_denied"
+ // AuditActionInvitationSent fires when an Owner issues a new
+ // tenant invitation. Actor is the inviter, TargetUserID is the
+ // invitee. Note: AuditActionMemberAdded only fires when the
+ // invitee actually accepts and the tenant_members row is created.
+ AuditActionInvitationSent AuditAction = "rbac.invitation_sent"
+ // AuditActionInvitationAccepted fires when the invitee accepts a
+ // pending invitation. Actor is the invitee (acting on their own
+ // inbox); the matching rbac.member_added is emitted in the same
+ // transaction.
+ AuditActionInvitationAccepted AuditAction = "rbac.invitation_accepted"
+ // AuditActionInvitationDeclined fires when the invitee rejects a
+ // pending invitation. Actor and target are the same user.
+ AuditActionInvitationDeclined AuditAction = "rbac.invitation_declined"
+ // AuditActionInvitationRevoked fires when a tenant Owner cancels
+ // a still-pending invitation before the invitee acts. Actor is
+ // the Owner; target is the invitee.
+ AuditActionInvitationRevoked AuditAction = "rbac.invitation_revoked"
+ // AuditActionInvitationExpired fires when the lazy sweep transitions
+ // an overdue pending row to expired. Actor is empty (system).
+ AuditActionInvitationExpired AuditAction = "rbac.invitation_expired"
)
// AuditOutcome distinguishes successful mutations from middleware-level
diff --git a/internal/types/interfaces/tenant_invitation.go b/internal/types/interfaces/tenant_invitation.go
new file mode 100644
index 000000000..00af899d4
--- /dev/null
+++ b/internal/types/interfaces/tenant_invitation.go
@@ -0,0 +1,74 @@
+package interfaces
+
+import (
+ "context"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// TenantInvitationRepository persists tenant_invitations rows that
+// capture the "pending invite" intent before it becomes a real
+// tenant_members row. All read methods skip GORM soft-deleted rows.
+type TenantInvitationRepository interface {
+ // Create inserts a new pending invitation. Returns the conflict
+ // error sentinel (ErrPendingInvitationExists) if the (tenant_id,
+ // invitee) partial unique index rejects the insert.
+ Create(ctx context.Context, inv *types.TenantInvitation) error
+
+ // GetByID fetches an invitation by surrogate id, or (nil, nil) if
+ // missing. Used by Accept/Decline/Revoke handlers.
+ GetByID(ctx context.Context, id uint64) (*types.TenantInvitation, error)
+
+ // GetPendingByPair returns the in-flight pending invitation for
+ // (tenant, invitee) or (nil, nil) when none exists. Used by the
+ // service layer to short-circuit duplicate Create calls before
+ // they hit the unique index.
+ GetPendingByPair(ctx context.Context, tenantID uint64, inviteeUserID string) (*types.TenantInvitation, error)
+
+ // ListByTenant returns invitations for the tenant ordered by
+ // id DESC (newest first). includeTerminal controls whether
+ // non-pending rows (accepted/declined/revoked/expired) are
+ // returned — the management UI shows pending by default, with
+ // a "history" toggle for the rest.
+ ListByTenant(ctx context.Context, tenantID uint64, includeTerminal bool) ([]*types.TenantInvitation, error)
+
+ // CountByTenantList counts invitation rows matching the same filter as
+ // ListByTenant (tenant_id + optional pending-only vs include-terminal).
+ CountByTenantList(ctx context.Context, tenantID uint64, includeTerminal bool) (int64, error)
+
+ // ListByTenantPage returns invitations for the tenant with id DESC
+ // paging, same filtering semantics as ListByTenant.
+ ListByTenantPage(ctx context.Context, tenantID uint64, includeTerminal bool, offset, limit int) ([]*types.TenantInvitation, error)
+
+ // ListByInvitee returns invitations addressed to the user across
+ // all tenants. Ordered by id DESC. Used both by the inbox page
+ // (includeTerminal=false) and by /me/invitations/history if/when
+ // we expose history (includeTerminal=true).
+ ListByInvitee(ctx context.Context, inviteeUserID string, includeTerminal bool) ([]*types.TenantInvitation, error)
+
+ // CountPendingByInvitee returns the number of pending invitations
+ // for the user. Used by the avatar-row badge so the UI doesn't
+ // have to fetch the full list just to render a count.
+ CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
+
+ // MarkStatusIfPending atomically transitions a row from pending
+ // to the supplied status. respondedAt is recorded as the
+ // transition time. Returns gorm.ErrRecordNotFound when the row
+ // does not exist or is already in a non-pending state, which the
+ // service layer maps to ErrInvitationNotPending — that error is
+ // the "stale state machine" signal callers care about.
+ MarkStatusIfPending(
+ ctx context.Context,
+ id uint64,
+ status types.TenantInvitationStatus,
+ respondedAt time.Time,
+ ) error
+
+ // SweepExpired transitions all pending rows whose expires_at is
+ // before `now` into the expired state. Returns the affected row
+ // count so callers can decide whether to emit per-row audit
+ // events (we don't — the volume could be high and the audit-log
+ // table already records the original invitation_sent rows).
+ SweepExpired(ctx context.Context, now time.Time) (int64, error)
+}
diff --git a/internal/types/interfaces/tenant_invitation_service.go b/internal/types/interfaces/tenant_invitation_service.go
new file mode 100644
index 000000000..594a56da0
--- /dev/null
+++ b/internal/types/interfaces/tenant_invitation_service.go
@@ -0,0 +1,67 @@
+package interfaces
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// TenantInvitationService is the business-logic layer over
+// TenantInvitationRepository. It enforces the lifecycle invariants
+// described in TenantInvitationStatus, runs the lazy expiry sweep, and
+// brokers the accept-time hand-off into TenantMemberService so that
+// "accept" produces both the invitation transition AND the
+// tenant_members row in a single audit story.
+type TenantInvitationService interface {
+ // Create issues a new pending invitation for (tenantID, inviteeUserID)
+ // with the given role. Caller passes the inviter user id (may be
+ // nil for service-internal flows). Returns the freshly created row
+ // or a sentinel error (ErrPendingInvitationExists / ErrAlreadyMember /
+ // ErrInvalidTenantRole) for the common conflicts.
+ Create(
+ ctx context.Context,
+ tenantID uint64,
+ inviteeUserID string,
+ role types.TenantRole,
+ invitedBy *string,
+ message string,
+ ) (*types.TenantInvitation, error)
+
+ // Accept transitions the pending row into accepted AND creates the
+ // active tenant_members row in the same transaction. The callerUserID
+ // MUST equal inv.InviteeUserID — the service rejects anyone else.
+ // Returns the freshly created membership for the response shape.
+ Accept(ctx context.Context, invID uint64, callerUserID string) (*types.TenantMember, error)
+
+ // Decline transitions the pending row into declined. Same caller
+ // rule as Accept: only the invitee themselves.
+ Decline(ctx context.Context, invID uint64, callerUserID string) error
+
+ // Revoke transitions the pending row into revoked. Callable by an
+ // Owner of the tenant the invitation belongs to (the handler
+ // applies the Owner gate via g.Owner() route middleware, so this
+ // method does not re-check role).
+ Revoke(ctx context.Context, invID uint64) error
+
+ // GetByID returns an invitation or (nil, nil). Used by handlers to
+ // authorise per-row operations (e.g. is the caller the invitee?).
+ GetByID(ctx context.Context, invID uint64) (*types.TenantInvitation, error)
+
+ // ListByTenant returns invitations for a tenant. Always runs the
+ // lazy expiry sweep before reading so stale-pending rows surface
+ // as expired in the UI.
+ ListByTenant(ctx context.Context, tenantID uint64, includeTerminal bool) ([]*types.TenantInvitation, error)
+
+ // ListTenantInvitationsPage paginates invitations for the tenant
+ // management UI after the lazy sweep (same filtering as ListByTenant).
+ ListTenantInvitationsPage(ctx context.Context, tenantID uint64, includeTerminal bool, page, pageSize int) ([]*types.TenantInvitation, int64, error)
+
+ // ListByInvitee returns invitations addressed to the user across
+ // all tenants. Always runs the lazy sweep first.
+ ListByInvitee(ctx context.Context, inviteeUserID string, includeTerminal bool) ([]*types.TenantInvitation, error)
+
+ // CountPendingByInvitee returns the user's pending invitation count
+ // after running the lazy sweep, so the inbox badge can poll a
+ // lightweight endpoint without paginating the full list.
+ CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
+}
diff --git a/internal/types/interfaces/tenant_member.go b/internal/types/interfaces/tenant_member.go
index c29f66b6e..3f95d43b2 100644
--- a/internal/types/interfaces/tenant_member.go
+++ b/internal/types/interfaces/tenant_member.go
@@ -30,6 +30,16 @@ type TenantMemberRepository interface {
// ordered by joined_at ascending.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
+ // CountFilteredByTenant counts active memberships in tenant. Optional
+ // search matches user email/username (join users table); empty search
+ // counts all memberships.
+ CountFilteredByTenant(ctx context.Context, tenantID uint64, search string) (int64, error)
+
+ // ListPagedByTenant returns active memberships sorted joined_at ASC, id ASC.
+ // search filters by user email/username (join users table); empty
+ // search lists all memberships in tenant.
+ ListPagedByTenant(ctx context.Context, tenantID uint64, search string, offset, limit int) ([]*types.TenantMember, error)
+
// UpdateRole changes the role of an existing active membership. Returns
// gorm.ErrRecordNotFound if no active row matches.
UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error
diff --git a/internal/types/interfaces/tenant_member_service.go b/internal/types/interfaces/tenant_member_service.go
index 4ead2f31d..43851dfe4 100644
--- a/internal/types/interfaces/tenant_member_service.go
+++ b/internal/types/interfaces/tenant_member_service.go
@@ -33,6 +33,10 @@ type TenantMemberService interface {
// ListByTenant returns every active membership inside the tenant.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
+ // ListMembersPage lists members with pagination. Query matches email or
+ // username case-insensitively; empty query returns full tenant list slice.
+ ListMembersPage(ctx context.Context, tenantID uint64, query string, page, pageSize int) ([]*types.TenantMember, int64, error)
+
// HasAnyMembers reports whether the tenant has at least one active
// member. The auth middleware uses this to recover orphan tenants
// (e.g. API-key-only tenants that never had a human member): the
diff --git a/internal/types/tenant_invitation.go b/internal/types/tenant_invitation.go
new file mode 100644
index 000000000..cf1692e79
--- /dev/null
+++ b/internal/types/tenant_invitation.go
@@ -0,0 +1,125 @@
+package types
+
+import (
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// TenantInvitationStatus enumerates the lifecycle states of a single
+// invitation row. The legal transitions are:
+//
+// pending -> accepted | declined | revoked | expired
+//
+// All non-pending states are terminal; once a row leaves pending it is
+// kept for the audit trail and a new pending row can be issued.
+type TenantInvitationStatus string
+
+const (
+ // TenantInvitationStatusPending is the initial state: the invitee
+ // has not yet acted and the row has not been revoked or aged out.
+ TenantInvitationStatusPending TenantInvitationStatus = "pending"
+ // TenantInvitationStatusAccepted means the invitee confirmed and
+ // a corresponding active tenant_members row has been created in
+ // the same transaction.
+ TenantInvitationStatusAccepted TenantInvitationStatus = "accepted"
+ // TenantInvitationStatusDeclined means the invitee rejected the
+ // invitation. The row stays for auditability; a new pending
+ // invitation can be issued afterwards.
+ TenantInvitationStatusDeclined TenantInvitationStatus = "declined"
+ // TenantInvitationStatusRevoked means a tenant Owner cancelled
+ // the pending invitation before the invitee acted.
+ TenantInvitationStatusRevoked TenantInvitationStatus = "revoked"
+ // TenantInvitationStatusExpired means the row outlived its
+ // expires_at without being accepted/declined/revoked. Set by the
+ // lazy-sweep run before every List/Accept/Decline.
+ TenantInvitationStatusExpired TenantInvitationStatus = "expired"
+)
+
+// IsTerminal reports whether s is a non-pending state. Used by the
+// service layer to short-circuit accept/decline/revoke on rows that
+// have already been finalised.
+func (s TenantInvitationStatus) IsTerminal() bool {
+ switch s {
+ case TenantInvitationStatusAccepted,
+ TenantInvitationStatusDeclined,
+ TenantInvitationStatusRevoked,
+ TenantInvitationStatusExpired:
+ return true
+ }
+ return false
+}
+
+// TenantInvitation is one pending or finalised invitation issued by an
+// Owner of `TenantID` to the user identified by `InviteeUserID`. The
+// row is created in `pending` state when the Owner clicks "invite"; it
+// flips to a terminal state when the invitee accepts/declines, the
+// Owner revokes, or the row expires.
+//
+// A tenant_members row is created only on accept; the invitation table
+// is therefore the single source of truth for "pending intent" without
+// polluting the authoritative member roster.
+type TenantInvitation struct {
+ // Surrogate primary key.
+ ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
+ // TenantID references tenants.id.
+ TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
+ // InviteeUserID references users.id (always a registered user; the
+ // handler resolves the email to a User row before insertion).
+ InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;index"`
+ // InvitedBy records the user id that issued this invitation. NULL
+ // for invitations created via service-internal / synthetic actors
+ // (mirrors the same treatment TenantMember.InvitedBy gets).
+ InvitedBy *string `json:"invited_by,omitempty" gorm:"type:varchar(36)"`
+ // Role the invitee will receive in tenant_members if they accept.
+ Role TenantRole `json:"role" gorm:"type:varchar(20);not null"`
+ // Status holds the lifecycle state. Default pending; mutated to
+ // accepted/declined/revoked/expired exactly once.
+ Status TenantInvitationStatus `json:"status" gorm:"type:varchar(20);not null;default:'pending'"`
+ // Message is an optional free-text note the Owner can include in
+ // the invitation (e.g. "joining the design squad — welcome!").
+ Message string `json:"message,omitempty" gorm:"type:varchar(500)"`
+ // ExpiresAt is when this row auto-flips to expired if still pending.
+ // Set at creation time from RBAC_INVITATION_TTL (default 7d).
+ ExpiresAt time.Time `json:"expires_at"`
+ // RespondedAt records when the row left pending. Nil while pending.
+ RespondedAt *time.Time `json:"responded_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
+}
+
+// TableName binds TenantInvitation to the tenant_invitations table.
+func (TenantInvitation) TableName() string { return "tenant_invitations" }
+
+// IsExpired reports whether this invitation is past its expires_at at
+// the given reference time. The service layer uses this both for the
+// lazy sweep and to reject an accept/decline arriving after timeout.
+func (inv *TenantInvitation) IsExpired(at time.Time) bool {
+ if inv == nil || inv.ExpiresAt.IsZero() {
+ return false
+ }
+ return inv.ExpiresAt.Before(at)
+}
+
+// TenantInvitationResponse is the API projection joined with tenant
+// name and inviter / invitee user fields the UI needs. The model is
+// intentionally NOT serialised directly so we don't leak DeletedAt /
+// UpdatedAt and lock the DB schema into the public API.
+type TenantInvitationResponse struct {
+ ID uint64 `json:"id"`
+ TenantID uint64 `json:"tenant_id"`
+ TenantName string `json:"tenant_name,omitempty"`
+ InviteeUserID string `json:"invitee_user_id"`
+ InviteeEmail string `json:"invitee_email,omitempty"`
+ InviteeName string `json:"invitee_name,omitempty"`
+ InvitedBy *string `json:"invited_by,omitempty"`
+ InviterEmail string `json:"inviter_email,omitempty"`
+ InviterName string `json:"inviter_name,omitempty"`
+ Role TenantRole `json:"role"`
+ Status TenantInvitationStatus `json:"status"`
+ Message string `json:"message,omitempty"`
+ ExpiresAt time.Time `json:"expires_at"`
+ RespondedAt *time.Time `json:"responded_at,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+}
diff --git a/migrations/sqlite/000000_init.down.sql b/migrations/sqlite/000000_init.down.sql
index 72ea402cf..db0c4595c 100644
--- a/migrations/sqlite/000000_init.down.sql
+++ b/migrations/sqlite/000000_init.down.sql
@@ -1,3 +1,4 @@
+DROP TABLE IF EXISTS tenant_invitations;
DROP TABLE IF EXISTS user_resource_favorites;
DROP TABLE IF EXISTS tenant_disabled_shared_agents;
DROP TABLE IF EXISTS agent_shares;
diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql
index 1e37a80e4..50e313b1d 100644
--- a/migrations/sqlite/000000_init.up.sql
+++ b/migrations/sqlite/000000_init.up.sql
@@ -315,6 +315,31 @@ CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_user_tenant_type_created_
CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_tenant_id
ON user_resource_favorites(tenant_id);
+-- tenant_invitations — sqlite mirror of migration 000048. SQLite supports
+-- partial unique indexes too, so the same "one pending per (tenant,
+-- invitee)" guard can be applied verbatim.
+CREATE TABLE IF NOT EXISTS tenant_invitations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ tenant_id INTEGER NOT NULL,
+ invitee_user_id VARCHAR(36) NOT NULL,
+ invited_by VARCHAR(36),
+ role VARCHAR(20) NOT NULL,
+ status VARCHAR(20) NOT NULL DEFAULT 'pending',
+ message VARCHAR(500),
+ expires_at DATETIME NOT NULL,
+ responded_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ deleted_at DATETIME
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_tenant_invitations_unique_pending
+ ON tenant_invitations(tenant_id, invitee_user_id)
+ WHERE status = 'pending' AND deleted_at IS NULL;
+CREATE INDEX IF NOT EXISTS idx_tenant_invitations_tenant
+ ON tenant_invitations(tenant_id);
+CREATE INDEX IF NOT EXISTS idx_tenant_invitations_invitee
+ ON tenant_invitations(invitee_user_id);
+
CREATE TABLE IF NOT EXISTS knowledge_tags (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
diff --git a/migrations/versioned/000048_tenant_invitations.down.sql b/migrations/versioned/000048_tenant_invitations.down.sql
new file mode 100644
index 000000000..0a2aafe4a
--- /dev/null
+++ b/migrations/versioned/000048_tenant_invitations.down.sql
@@ -0,0 +1,9 @@
+-- Reverse of 000048_tenant_invitations.
+DO $$ BEGIN RAISE NOTICE '[Migration 000048] Dropping table: tenant_invitations'; END $$;
+
+DROP INDEX IF EXISTS idx_tenant_invitations_invitee;
+DROP INDEX IF EXISTS idx_tenant_invitations_tenant;
+DROP INDEX IF EXISTS idx_tenant_invitations_unique_pending;
+DROP TABLE IF EXISTS tenant_invitations;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000048] tenant_invitations table dropped'; END $$;
diff --git a/migrations/versioned/000048_tenant_invitations.up.sql b/migrations/versioned/000048_tenant_invitations.up.sql
new file mode 100644
index 000000000..2ff15cf5c
--- /dev/null
+++ b/migrations/versioned/000048_tenant_invitations.up.sql
@@ -0,0 +1,59 @@
+-- Migration: 000048_tenant_invitations
+-- Adds an explicit "invitation -> accept" flow on top of the
+-- tenant-member RBAC model introduced in 000043. Previously, POST
+-- /tenants/:id/members wrote an active tenant_members row in one shot
+-- so the invitee was added without their knowledge or consent. The
+-- table below records the pending intent; the row is only promoted
+-- into a real tenant_members entry after the invitee accepts.
+--
+-- Why a separate table instead of reusing tenant_members.status='invited':
+-- - Mixing the two states pollutes every existing tenant_members
+-- read path with an extra "AND status='active'" filter, and the
+-- PRs that introduced kb / agent ownership already assume any
+-- non-deleted membership is active.
+-- - Declined / revoked / expired invitations carry forensic value
+-- (e.g. "did Bob ever try to add Eve?"); keeping them in their
+-- own table lets us retain the full history without touching the
+-- authoritative roster.
+-- - Re-inviting the same user is a natural use case; a separate
+-- table accumulates rows naturally with a partial unique index
+-- guarding the in-flight one.
+--
+-- Status machine:
+-- pending -> accepted (terminal; invitee accepts)
+-- pending -> declined (terminal; invitee rejects)
+-- pending -> revoked (terminal; owner cancels)
+-- pending -> expired (terminal; lazy sweep after expires_at)
+DO $$ BEGIN RAISE NOTICE '[Migration 000048] Creating table: tenant_invitations'; END $$;
+
+CREATE TABLE IF NOT EXISTS tenant_invitations (
+ id BIGSERIAL PRIMARY KEY,
+ tenant_id INTEGER NOT NULL,
+ invitee_user_id VARCHAR(36) NOT NULL,
+ invited_by VARCHAR(36),
+ role VARCHAR(20) NOT NULL,
+ status VARCHAR(20) NOT NULL DEFAULT 'pending',
+ message VARCHAR(500),
+ expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
+ responded_at TIMESTAMP WITH TIME ZONE,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ deleted_at TIMESTAMP WITH TIME ZONE
+);
+
+-- Partial unique index: at most one PENDING invitation per (tenant,
+-- invitee). Terminal-state rows (accepted/declined/revoked/expired)
+-- can accumulate freely so the history of past invites stays intact.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_tenant_invitations_unique_pending
+ ON tenant_invitations(tenant_id, invitee_user_id)
+ WHERE status = 'pending' AND deleted_at IS NULL;
+
+-- Read paths:
+-- - Tenant management UI: list invitations for a tenant.
+-- - "My invitations" inbox: list invitations for a user.
+CREATE INDEX IF NOT EXISTS idx_tenant_invitations_tenant
+ ON tenant_invitations(tenant_id) WHERE deleted_at IS NULL;
+CREATE INDEX IF NOT EXISTS idx_tenant_invitations_invitee
+ ON tenant_invitations(invitee_user_id) WHERE deleted_at IS NULL;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000048] tenant_invitations table ready'; END $$;