feat(invitations): implement pending invitations feature with polling and dialog
Added functionality for managing pending invitations, including a polling mechanism to update the invitation count in real-time. Introduced a new dialog component for users to view and respond to their invitations without navigating away from their current context. Updated API endpoints for fetching and managing invitations, and enhanced the user interface with relevant internationalization support. Refs: #1303
This commit is contained in:
+55
-17
@@ -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>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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): Promise<ListMembersResponse> {
|
||||
return (await get(`/api/v1/tenants/${tenantId}/members`)) as unknown as ListMembersResponse
|
||||
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 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
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
<template>
|
||||
<!-- "My invitations" inbox as a dialog. The previous version of
|
||||
this was a full /platform/invitations route, but the inbox is
|
||||
intrinsically transient — open it, act, dismiss — and a modal
|
||||
keeps the user in whatever context the bell icon was clicked
|
||||
from rather than yanking them to a separate page. The trigger
|
||||
lives in UserMenu's avatar-row bell. -->
|
||||
<t-dialog v-model:visible="visibleModel" :header="$t('tenantInvitation.myInbox.title')" :footer="false" width="540px"
|
||||
:close-on-overlay-click="true">
|
||||
<p class="my-invitations-desc">{{ $t('tenantInvitation.myInbox.description') }}</p>
|
||||
|
||||
<div v-if="loading" class="loading-inline">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('tenantMember.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else-if="error" class="error-inline">
|
||||
<t-alert theme="error" :message="error">
|
||||
<template #operation>
|
||||
<t-button size="small" @click="reload">{{ $t('tenantMember.retry') }}</t-button>
|
||||
</template>
|
||||
</t-alert>
|
||||
</div>
|
||||
|
||||
<div v-else-if="invitations.length === 0" class="empty-state">
|
||||
<t-empty :description="$t('tenantInvitation.myInbox.empty')" />
|
||||
</div>
|
||||
|
||||
<ul v-else class="invitation-list">
|
||||
<li v-for="row in invitations" :key="row.id" class="invitation-card">
|
||||
<div class="invitation-card-main">
|
||||
<div class="invitation-card-header">
|
||||
<span class="tenant-name">
|
||||
{{ row.tenant_name || $t('tenantInvitation.myInbox.tenantLabel') + ' #' + row.tenant_id }}
|
||||
</span>
|
||||
<t-tag :theme="roleTagTheme(row.role)" size="small">
|
||||
{{ $t('tenantMember.role.' + row.role) }}
|
||||
</t-tag>
|
||||
</div>
|
||||
<div class="invitation-card-meta">
|
||||
<span class="meta-row">
|
||||
<t-icon name="user" size="14px" class="meta-icon" />
|
||||
<span class="meta-label">{{ $t('tenantInvitation.myInbox.from') }}:</span>
|
||||
<span class="meta-value">{{ inviterDisplay(row) }}</span>
|
||||
</span>
|
||||
<span class="meta-row">
|
||||
<t-icon name="time" size="14px" class="meta-icon" />
|
||||
<span class="meta-value">
|
||||
{{ $t('tenantInvitation.myInbox.expiresIn', { date: formatDate(row.expires_at) }) }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="row.message" class="meta-row meta-row--message">
|
||||
<t-icon name="chat" size="14px" class="meta-icon" />
|
||||
<span class="meta-label">{{ $t('tenantInvitation.myInbox.messageLabel') }}:</span>
|
||||
<span class="meta-value">{{ row.message }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="invitation-card-actions">
|
||||
<t-button theme="primary" size="small" :loading="acting === row.id" @click="onAccept(row)">
|
||||
{{ $t('tenantInvitation.myInbox.acceptButton') }}
|
||||
</t-button>
|
||||
<t-button theme="default" variant="outline" size="small" :loading="acting === row.id" @click="onDecline(row)">
|
||||
{{ $t('tenantInvitation.myInbox.declineButton') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</t-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import {
|
||||
listMyInvitations,
|
||||
acceptInvitation,
|
||||
declineInvitation,
|
||||
type TenantInvitation,
|
||||
} from '@/api/tenant/invitations'
|
||||
import type { TenantRole } from '@/api/tenant/members'
|
||||
|
||||
// v-model:visible — the parent (UserMenu) owns the open/close state
|
||||
// so the bell icon stays the single source of truth. Reload is run
|
||||
// on every open transition so the list reflects accept/decline
|
||||
// actions taken in another tab while the dialog was closed.
|
||||
const props = defineProps<{ visible: boolean }>()
|
||||
const emit = defineEmits<{ (e: 'update:visible', v: boolean): void }>()
|
||||
const visibleModel = computed({
|
||||
get: () => props.visible,
|
||||
set: (v) => emit('update:visible', v),
|
||||
})
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const invitations = ref<TenantInvitation[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const acting = ref<number | null>(null)
|
||||
|
||||
function roleTagTheme(role: TenantRole): 'primary' | 'warning' | 'success' | 'default' {
|
||||
switch (role) {
|
||||
case 'owner':
|
||||
return 'primary'
|
||||
case 'admin':
|
||||
return 'warning'
|
||||
case 'contributor':
|
||||
return 'success'
|
||||
default:
|
||||
return 'default'
|
||||
}
|
||||
}
|
||||
|
||||
function inviterDisplay(row: TenantInvitation): string {
|
||||
return row.inviter_name?.trim() || row.inviter_email?.trim() || row.invited_by || '—'
|
||||
}
|
||||
|
||||
function formatDate(s: string): string {
|
||||
if (!s) return '-'
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale.value || 'zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(s))
|
||||
} catch {
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const resp = await listMyInvitations()
|
||||
if (resp.success && resp.data) {
|
||||
invitations.value = resp.data.invitations
|
||||
authStore.setPendingInvitationCount(
|
||||
invitations.value.filter((i) => i.status === 'pending').length,
|
||||
)
|
||||
} else {
|
||||
error.value = resp.message || t('tenantInvitation.errors.generic')
|
||||
}
|
||||
} catch (err: any) {
|
||||
error.value = err?.message || t('tenantInvitation.errors.generic')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onAccept(row: TenantInvitation) {
|
||||
acting.value = row.id
|
||||
try {
|
||||
const resp = await acceptInvitation(row.id)
|
||||
if (resp.success) {
|
||||
invitations.value = invitations.value.filter((x) => x.id !== row.id)
|
||||
authStore.setPendingInvitationCount(Math.max(0, authStore.pendingInvitationCount - 1))
|
||||
await authStore.refreshFromAuthMe()
|
||||
MessagePlugin.success(
|
||||
t('tenantInvitation.myInbox.acceptSuccess', {
|
||||
tenant: row.tenant_name || `#${row.tenant_id}`,
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
|
||||
}
|
||||
} catch (err: any) {
|
||||
const status = err?.status
|
||||
if (status === 404) MessagePlugin.error(t('tenantInvitation.errors.notFound'))
|
||||
else if (status === 403) MessagePlugin.error(t('tenantInvitation.errors.forbidden'))
|
||||
else if (status === 409) MessagePlugin.error(err?.message || t('tenantInvitation.errors.notPending'))
|
||||
else MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
|
||||
} finally {
|
||||
acting.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function onDecline(row: TenantInvitation) {
|
||||
acting.value = row.id
|
||||
try {
|
||||
const resp = await declineInvitation(row.id)
|
||||
if (resp.success) {
|
||||
invitations.value = invitations.value.filter((x) => x.id !== row.id)
|
||||
authStore.setPendingInvitationCount(Math.max(0, authStore.pendingInvitationCount - 1))
|
||||
MessagePlugin.success(t('tenantInvitation.myInbox.declineSuccess'))
|
||||
} else {
|
||||
MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
|
||||
}
|
||||
} catch (err: any) {
|
||||
const status = err?.status
|
||||
if (status === 404) MessagePlugin.error(t('tenantInvitation.errors.notFound'))
|
||||
else if (status === 403) MessagePlugin.error(t('tenantInvitation.errors.forbidden'))
|
||||
else if (status === 409) MessagePlugin.error(err?.message || t('tenantInvitation.errors.notPending'))
|
||||
else MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
|
||||
} finally {
|
||||
acting.value = null
|
||||
}
|
||||
}
|
||||
|
||||
// Refetch on every open. Costs one round-trip but the user clicked
|
||||
// here specifically to see the latest state; serving stale data
|
||||
// would only confuse the empty-state vs "1 invitation" cases.
|
||||
watch(
|
||||
() => props.visible,
|
||||
(v) => {
|
||||
if (v) reload()
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.my-invitations-desc {
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
margin: 0 0 16px 0;
|
||||
}
|
||||
|
||||
.loading-inline,
|
||||
.error-inline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 16px 0 8px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.invitation-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
/* Cap height so a user with many invitations can scroll within
|
||||
the dialog rather than the dialog growing past the viewport. */
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.invitation-card {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
background: var(--td-bg-color-container);
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 8px;
|
||||
|
||||
.invitation-card-main {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.invitation-card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.tenant-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.invitation-card-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: 12px;
|
||||
|
||||
.meta-row {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
|
||||
.meta-icon {
|
||||
color: var(--td-text-color-placeholder);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.meta-value {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&--message {
|
||||
align-items: flex-start;
|
||||
|
||||
.meta-icon {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.meta-value {
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.invitation-card-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -16,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()
|
||||
|
||||
@@ -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%;
|
||||
|
||||
@@ -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.',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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: "작업에 실패했습니다. 다시 시도해 주세요.",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4358,6 +4358,8 @@ export default {
|
||||
title: 'Участники',
|
||||
sectionDescription: 'Приглашайте коллег в тенант и управляйте их ролями. Добавлять и удалять участников может только Владелец.',
|
||||
totalCount: 'Участников: {n}',
|
||||
listTitle: 'Участники пространства',
|
||||
filterMatched: 'найдено: {n}',
|
||||
loading: 'Загрузка участников…',
|
||||
retry: 'Повторить',
|
||||
empty: 'Участников пока нет. Пригласите коллегу, чтобы начать.',
|
||||
|
||||
@@ -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: "操作失败,请稍后重试。",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 $$;
|
||||
@@ -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 $$;
|
||||
Reference in New Issue
Block a user