From 884ac44283fc9c2bce66495809953fe928e8248e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Sun, 17 May 2026 21:19:59 +0800 Subject: [PATCH] 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 --- frontend/src/App.vue | 72 +- frontend/src/api/tenant/invitations.ts | 193 +++ frontend/src/api/tenant/members.ts | 56 +- .../src/components/MyInvitationsDialog.vue | 325 ++++ frontend/src/components/TenantSelector.vue | 47 +- frontend/src/components/UserMenu.vue | 112 +- frontend/src/i18n/locales/en-US.ts | 68 + frontend/src/i18n/locales/ko-KR.ts | 64 + frontend/src/i18n/locales/ru-RU.ts | 2 + frontend/src/i18n/locales/zh-CN.ts | 67 + frontend/src/stores/auth.ts | 91 ++ frontend/src/views/settings/TenantInfo.vue | 7 +- frontend/src/views/settings/TenantMembers.vue | 1408 +++++++++++++---- .../repository/tenant_invitation.go | 257 +++ .../application/repository/tenant_member.go | 51 + .../application/service/tenant_invitation.go | 430 +++++ .../service/tenant_invitation_test.go | 397 +++++ internal/application/service/tenant_member.go | 36 + .../application/service/tenant_member_test.go | 46 + internal/container/container.go | 3 + internal/handler/list_pagination.go | 42 + internal/handler/tenant_invitation.go | 506 ++++++ internal/handler/tenant_member.go | 41 +- internal/handler/tenant_member_test.go | 52 +- internal/middleware/auth_role_test.go | 5 + internal/router/router.go | 46 +- internal/types/audit_log.go | 20 + .../types/interfaces/tenant_invitation.go | 74 + .../interfaces/tenant_invitation_service.go | 67 + internal/types/interfaces/tenant_member.go | 10 + .../types/interfaces/tenant_member_service.go | 4 + internal/types/tenant_invitation.go | 125 ++ migrations/sqlite/000000_init.down.sql | 1 + migrations/sqlite/000000_init.up.sql | 25 + .../000048_tenant_invitations.down.sql | 9 + .../000048_tenant_invitations.up.sql | 59 + 36 files changed, 4378 insertions(+), 440 deletions(-) create mode 100644 frontend/src/api/tenant/invitations.ts create mode 100644 frontend/src/components/MyInvitationsDialog.vue create mode 100644 internal/application/repository/tenant_invitation.go create mode 100644 internal/application/service/tenant_invitation.go create mode 100644 internal/application/service/tenant_invitation_test.go create mode 100644 internal/handler/list_pagination.go create mode 100644 internal/handler/tenant_invitation.go create mode 100644 internal/types/interfaces/tenant_invitation.go create mode 100644 internal/types/interfaces/tenant_invitation_service.go create mode 100644 internal/types/tenant_invitation.go create mode 100644 migrations/versioned/000048_tenant_invitations.down.sql create mode 100644 migrations/versioned/000048_tenant_invitations.up.sql diff --git a/frontend/src/App.vue b/frontend/src/App.vue index aa40b0c8..79c69773 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,5 +1,5 @@ @@ -188,29 +226,29 @@ onUnmounted(() => { diff --git a/frontend/src/api/tenant/invitations.ts b/frontend/src/api/tenant/invitations.ts new file mode 100644 index 00000000..eda2aa2c --- /dev/null +++ b/frontend/src/api/tenant/invitations.ts @@ -0,0 +1,193 @@ +import { get, post, del } from '@/utils/request' +import type { TenantRole } from '@/api/tenant/members' + +// TenantInvitationStatus mirrors internal/types/tenant_invitation.go's +// five-state machine. pending is the only non-terminal state; the rest +// are recorded for the audit trail. +export type TenantInvitationStatus = + | 'pending' + | 'accepted' + | 'declined' + | 'revoked' + | 'expired' + +// TenantInvitation is the API projection of a tenant_invitations row, +// hydrated with the inviter / invitee user fields and the tenant name +// when the backend has them. Missing optional fields render as the +// raw id in the UI rather than dropping the row. +export interface TenantInvitation { + id: number + tenant_id: number + tenant_name?: string + invitee_user_id: string + invitee_email?: string + invitee_name?: string + invited_by?: string | null + inviter_email?: string + inviter_name?: string + role: TenantRole + status: TenantInvitationStatus + message?: string + expires_at: string + responded_at?: string | null + created_at: string +} + +export interface ListInvitationsResponse { + success: boolean + data?: { + invitations: TenantInvitation[] + total: number + page?: number + page_size?: number + } + message?: string +} + +export interface ListTenantInvitationsParams { + includeTerminal?: boolean + page?: number + page_size?: number +} + +function buildTenantInvitationsQuery(options: ListTenantInvitationsParams): string { + const u = new URLSearchParams() + if (options.includeTerminal) u.set('include_terminal', 'true') + if (options.page != null && options.page > 0) u.set('page', String(options.page)) + if (options.page_size != null && options.page_size > 0) u.set('page_size', String(options.page_size)) + const qs = u.toString() + return qs ? `?${qs}` : '' +} + +export interface CreateInvitationRequest { + email: string + role: TenantRole + message?: string +} + +export interface CreateInvitationResponse { + success: boolean + data?: TenantInvitation + message?: string +} + +export interface SimpleResponse { + success: boolean + message?: string +} + +export interface AcceptInvitationResponse { + success: boolean + data?: { + membership: { + tenant_id: number + role: TenantRole + status: string + joined_at: string + } + } + message?: string +} + +export interface PendingCountResponse { + success: boolean + data?: { pending_count: number } + message?: string +} + +/** + * List invitations for a tenant. Defaults to pending only; pass + * includeTerminal=true to also surface accepted/declined/revoked/ + * expired rows for the history view. Supports `page` / `page_size`. + * Backend: GET /api/v1/tenants/:id/invitations (Viewer+). + */ +export async function listTenantInvitations( + tenantId: number, + options: ListTenantInvitationsParams = {}, +): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + return (await post( + `/api/v1/me/invitations/${invId}/decline`, + )) as unknown as SimpleResponse +} diff --git a/frontend/src/api/tenant/members.ts b/frontend/src/api/tenant/members.ts index b48e41b3..f7b9df86 100644 --- a/frontend/src/api/tenant/members.ts +++ b/frontend/src/api/tenant/members.ts @@ -24,10 +24,30 @@ export interface ListMembersResponse { data?: { members: TenantMember[] total: number + page?: number + page_size?: number } message?: string } +export interface ListMembersParams { + page?: number + page_size?: number + /** 按邮箱/用户名筛选(服务端模糊匹配) */ + q?: string +} + +function buildMembersQuery(params: ListMembersParams | undefined): string { + if (!params) return '' + const u = new URLSearchParams() + if (params.page != null && params.page > 0) u.set('page', String(params.page)) + if (params.page_size != null && params.page_size > 0) u.set('page_size', String(params.page_size)) + const q = params.q?.trim() + if (q) u.set('q', q) + const qs = u.toString() + return qs ? `?${qs}` : '' +} + export interface AddMemberRequest { email: string role: TenantRole @@ -45,11 +65,39 @@ export interface SimpleResponse { } /** - * List all active members of the given tenant. - * Backend: GET /api/v1/tenants/:id/members (Viewer+). + * 分页列出租户成员。 + * Backend: GET /api/v1/tenants/:id/members (Viewer+)。查询参数:`q`、`page`、`page_size`。 */ -export async function listMembers(tenantId: number): Promise { - return (await get(`/api/v1/tenants/${tenantId}/members`)) as unknown as ListMembersResponse +export async function listMembers( + tenantId: number, + params: ListMembersParams = {}, +): Promise { + 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 { + const pageSize = 100 + let page = 1 + const out: TenantMember[] = [] + let total = Number.POSITIVE_INFINITY + for (let guard = 0; guard < 500 && out.length < total; guard++) { + const resp = await listMembers(tenantId, { page, page_size: pageSize }) + if (!resp.success || !resp.data) break + total = resp.data.total + const batch = resp.data.members || [] + if (batch.length === 0 && page >= 2) break + out.push(...batch) + if (batch.length < pageSize) break + page++ + } + return out } /** diff --git a/frontend/src/components/MyInvitationsDialog.vue b/frontend/src/components/MyInvitationsDialog.vue new file mode 100644 index 00000000..fe217a7f --- /dev/null +++ b/frontend/src/components/MyInvitationsDialog.vue @@ -0,0 +1,325 @@ + + + + + diff --git a/frontend/src/components/TenantSelector.vue b/frontend/src/components/TenantSelector.vue index cb3d3774..92b4941f 100644 --- a/frontend/src/components/TenantSelector.vue +++ b/frontend/src/components/TenantSelector.vue @@ -16,37 +16,21 @@ {{ $t('tenant.switchTenant') }} - +
{{ $t('tenant.loading') }}
- + - +
{{ $t('tenant.noMatch') }}
- +
@@ -189,25 +173,25 @@ const selectTenant = (tenantId: number) => { const loadTenants = async (append = false) => { if (loading.value) return - + loading.value = true try { const keyword = searchQuery.value.trim() let tenantID: number | undefined = undefined - + // 如果是纯数字,同时作为 tenant_id 和 keyword 搜索 // 这样既能精确匹配租户ID,也能模糊匹配名称中包含数字的租户 if (keyword && /^\d+$/.test(keyword)) { tenantID = Number(keyword) } - + const response = await searchTenants({ keyword: keyword || undefined, tenant_id: tenantID, page: currentPage.value, page_size: pageSize.value }) - + if (response.success && response.data) { if (append) { tenants.value = [...tenants.value, ...response.data.items] @@ -231,7 +215,7 @@ const handleSearchInput = () => { if (searchTimer.value) { clearTimeout(searchTimer.value) } - + searchTimer.value = window.setTimeout(() => { currentPage.value = 1 tenants.value = [] @@ -261,13 +245,14 @@ const openCreateDialog = () => { createDialogVisible.value = true } -const onTenantCreated = (newTenant: TenantInfo) => { +const onTenantCreated = async (newTenant: TenantInfo) => { // 把新租户合并进当前列表并切过去。和 selectTenant 走同一条链路: // setSelectedTenant + navigateAfterTenantSwitch。后端 X-Tenant-ID 中 // 间件会查 tenant_members 校验,EnsureOwner 已经在后端写好 owner 行。 tenants.value = [newTenant, ...tenants.value.filter(t => t.id !== newTenant.id)] total.value = total.value + 1 authStore.setAllTenants(tenants.value) + await authStore.refreshFromAuthMe() authStore.setSelectedTenant(newTenant.id, newTenant.name) setTimeout(() => { navigateAfterTenantSwitch() diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index a22860a9..c6671547 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -24,6 +24,19 @@
{{ userEmail }}
+ + + + @@ -162,8 +175,8 @@ + as the IM submenu. Data comes from authStore.memberships, kept fresh via + GET /auth/me when the submenu opens (throttled) and after invite/create. -->
@@ -218,6 +231,7 @@ +
@@ -231,6 +245,7 @@ import { getCurrentUser, logout as logoutApi } from '@/api/auth' import { useI18n } from 'vue-i18n' import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue' import CreateTenantDialog from '@/components/CreateTenantDialog.vue' +import MyInvitationsDialog from '@/components/MyInvitationsDialog.vue' import { listAllIMChannels, type IMChannelOverview } from '@/api/agent' import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch' import type { TenantInfo } from '@/api/tenant' @@ -312,6 +327,25 @@ const toggleMenu = () => { menuVisible.value = !menuVisible.value } +// Pending invitation count surfaced as the trailing bell on the +// avatar row. Reads directly from the auth store so the App.vue +// poller and any local accept/decline updates flow through here +// without a separate fetch. The visual badge cap (99+) is handled +// by t-badge's max-count, so we just expose the raw count. +const pendingInvitationCount = computed(() => authStore.pendingInvitationCount) + +// Clicking the bell opens the invitations dialog inline. Previously +// this navigated to /platform/invitations, but the inbox is short- +// lived ("see what's pending, accept or decline, dismiss") and a +// dialog keeps the user in whatever context they came from. We +// also close the avatar dropdown if it's open so the modal doesn't +// fight with a stale hover panel. +const invitationsDialogVisible = ref(false) +const goToInvitations = () => { + menuVisible.value = false + invitationsDialogVisible.value = true +} + // 快捷导航到设置的特定部分 const handleQuickNav = (section: string) => { menuVisible.value = false @@ -373,19 +407,8 @@ const openCreateTenantDialog = () => { createTenantDialogVisible.value = true } -const onTenantCreated = (newTenant: TenantInfo) => { - // memberships 由 /auth/login 落库 + localStorage 缓存。这里追加一条 - // owner 进去让 hover 子菜单立即看到新租户;hard reload 后会被 - // /auth/me 的真实数据覆盖,状态不会长期失真。 - const next = [ - ...(authStore.memberships ?? []), - { - tenant_id: newTenant.id, - tenant_name: newTenant.name, - role: 'owner', - }, - ] - authStore.setMemberships(next) +const onTenantCreated = async (newTenant: TenantInfo) => { + await authStore.refreshFromAuthMe() authStore.setSelectedTenant(newTenant.id, newTenant.name) setTimeout(() => { navigateAfterTenantSwitch() @@ -395,11 +418,11 @@ const onTenantCreated = (newTenant: TenantInfo) => { // ---------- Tenant switcher submenu ---------- // // Same hover-driven submenu pattern as the IM panel above; data comes from -// authStore.memberships (populated by /auth/login). PR 4 of #1303 relaxed -// the X-Tenant-ID gate in middleware/auth.go to accept active membership -// rows, so flipping authStore.selectedTenantId here is enough — the next -// page reload re-issues every request with the new header and the server -// resolves the role server-side. +// authStore.memberships (refreshed from /auth/me when the submenu opens and +// after membership-changing actions). PR 4 of #1303 relaxed the X-Tenant-ID +// gate in middleware/auth.go to accept active membership rows, so flipping +// authStore.selectedTenantId here is enough — the next page reload re-issues +// every request with the new header and the server resolves the role server-side. type Membership = { tenant_id: number tenant_name?: string @@ -463,6 +486,9 @@ const switchToTenant = (m: Membership) => { }, 400) } +let lastTenantSubmenuMembershipRefresh = 0 +const TENANT_SUBMENU_MEMBERSHIP_REFRESH_MS = 2000 + const showTenantSubmenu = () => { if (tenantSubmenuHideTimer) { clearTimeout(tenantSubmenuHideTimer) @@ -471,6 +497,11 @@ const showTenantSubmenu = () => { positionTenantSubmenu() tenantSubmenuOpen.value = true clampFloatingToViewport('.tenant-submenu-floating', tenantSubmenuStyle) + const now = Date.now() + if (now - lastTenantSubmenuMembershipRefresh >= TENANT_SUBMENU_MEMBERSHIP_REFRESH_MS) { + lastTenantSubmenuMembershipRefresh = now + void authStore.refreshFromAuthMe() + } } const scheduleHideTenantSubmenu = () => { @@ -640,6 +671,10 @@ const loadUserInfo = async () => { updated_at: response.data.tenant.updated_at }) } + const membershipsSync = response.data.memberships + if (Array.isArray(membershipsSync)) { + authStore.setMemberships(membershipsSync) + } } } catch (error) { console.error('Failed to load user info:', error) @@ -818,6 +853,43 @@ onUnmounted(() => { transition: transform 0.2s; } +/* Pending-invitations bell, sits between user-info and the chevron. + The button itself is a transparent 28x28 click target sized to + match the avatar row's other trailing affordances; t-badge wraps + it and positions its own counter pill in the top-right via the + :offset prop, so we don't try to recreate badge positioning here. */ +.user-inbox-badge-wrap { + display: inline-flex; + align-items: center; + margin: 0 2px; + flex-shrink: 0; +} + +.user-inbox-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + border-radius: 8px; + background: transparent; + color: var(--td-text-color-secondary); + cursor: pointer; + transition: background-color 0.18s ease, color 0.18s ease; + + &:hover { + background-color: var(--td-bg-color-secondarycontainer); + color: var(--td-brand-color); + } + + &:focus-visible { + outline: 2px solid var(--td-brand-color-focus); + outline-offset: 1px; + } +} + .user-dropdown { position: absolute; bottom: 100%; diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 35350b62..39319ebe 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -4398,6 +4398,8 @@ export default { title: 'Members', sectionDescription: 'Invite teammates to the tenant and manage their roles. Only Owner can add or remove members.', totalCount: '{n} members', + listTitle: 'Workspace members', + filterMatched: '{n} matched', loading: 'Loading members…', retry: 'Retry', empty: 'No members yet. Invite a teammate to get started.', @@ -4494,6 +4496,11 @@ export default { 'rbac.member_role_changed': 'Role changed', 'rbac.member_left': 'Member left', 'rbac.access_denied': 'Access denied', + 'rbac.invitation_sent': 'Invitation sent', + 'rbac.invitation_accepted': 'Invitation accepted', + 'rbac.invitation_declined': 'Invitation declined', + 'rbac.invitation_revoked': 'Invitation revoked', + 'rbac.invitation_expired': 'Invitation expired', }, outcome: { success: 'Success', @@ -4501,4 +4508,65 @@ export default { }, }, }, + tenantInvitation: { + inboxTooltip: 'View pending invitations', + pendingSectionTitle: 'Pending invitations', + pendingSectionCount: '{n}', + pendingSectionDesc: + 'Awaiting the invitee to accept in their inbox. Auto-expires after {days} days.', + pendingEmpty: 'No pending invitations.', + inviteSubmit: 'Send invitation', + inviteSuccess: 'Invitation sent. Waiting for the invitee to accept.', + confirmInviteTitle: 'Send invitation?', + confirmInviteBody: + 'Send an invitation to {email} (role: {role}). They will join the tenant only after accepting.', + confirmSend: 'Send', + revoke: { + button: 'Revoke', + confirmTitle: 'Revoke invitation?', + confirmBody: + "After revoke, {email} can no longer accept this invitation. You can send a new one if needed.", + confirm: 'Revoke', + success: 'Invitation revoked.', + }, + columns: { + invitee: 'Invitee', + role: 'Role', + inviter: 'Inviter', + expiresAt: 'Expires', + status: 'Status', + operations: 'Actions', + }, + status: { + pending: 'Pending', + accepted: 'Accepted', + declined: 'Declined', + revoked: 'Revoked', + expired: 'Expired', + }, + myInbox: { + title: 'My invitations', + description: + 'Invitations from other tenants. Accept to join with the assigned role.', + empty: 'No pending invitations.', + acceptButton: 'Accept', + declineButton: 'Decline', + acceptSuccess: 'Joined "{tenant}".', + declineSuccess: 'Invitation declined.', + from: 'From', + tenantLabel: 'Tenant', + expiresIn: 'Expires: {date}', + messageLabel: 'Message', + gotoLink: 'Open inbox', + }, + errors: { + pendingExists: 'A pending invitation for this user already exists.', + alreadyMember: 'This user is already an active member of the tenant.', + notPending: 'The invitation is no longer pending.', + expired: 'The invitation has expired.', + forbidden: 'Only the invitee can accept or decline this invitation.', + notFound: 'Invitation not found or already withdrawn.', + generic: 'Something went wrong. Please try again.', + }, + }, } diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index f9fca319..798153d2 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -4458,6 +4458,8 @@ export default { title: "멤버 관리", sectionDescription: "테넌트에 동료를 초대하고 역할을 관리합니다. 소유자만 멤버를 추가하거나 제거할 수 있습니다.", totalCount: "총 {n}명", + listTitle: "워크스페이스 멤버", + filterMatched: "{n}명 일치", loading: "멤버를 불러오는 중…", retry: "다시 시도", empty: "아직 멤버가 없습니다. 동료를 초대해 시작하세요.", @@ -4554,6 +4556,11 @@ export default { "rbac.member_role_changed": "역할 변경", "rbac.member_left": "멤버 탈퇴", "rbac.access_denied": "접근 거부", + "rbac.invitation_sent": "초대 전송", + "rbac.invitation_accepted": "초대 수락", + "rbac.invitation_declined": "초대 거절", + "rbac.invitation_revoked": "초대 취소", + "rbac.invitation_expired": "초대 만료", }, outcome: { success: "성공", @@ -4561,4 +4568,61 @@ export default { }, }, }, + tenantInvitation: { + inboxTooltip: "대기 중인 초대 보기", + pendingSectionTitle: "대기 중인 초대", + pendingSectionCount: "{n}", + pendingSectionDesc: "수신자가 수락해야 멤버로 추가됩니다. {days}일 후 자동 만료.", + pendingEmpty: "대기 중인 초대가 없습니다.", + inviteSubmit: "초대 보내기", + inviteSuccess: "초대가 전송되었습니다.", + confirmInviteTitle: "초대를 보내시겠습니까?", + confirmInviteBody: "{email}에게 초대를 보냅니다(역할: {role}). 수락 후 멤버가 됩니다.", + confirmSend: "보내기", + revoke: { + button: "취소", + confirmTitle: "초대를 취소하시겠습니까?", + confirmBody: "취소 후 {email}은 이 초대를 수락할 수 없습니다.", + confirm: "취소", + success: "초대가 취소되었습니다.", + }, + columns: { + invitee: "초대 대상", + role: "역할", + inviter: "초대자", + expiresAt: "만료", + status: "상태", + operations: "작업", + }, + status: { + pending: "대기 중", + accepted: "수락됨", + declined: "거절됨", + revoked: "취소됨", + expired: "만료됨", + }, + myInbox: { + title: "내 초대", + description: "다른 워크스페이스의 초대 목록입니다.", + empty: "대기 중인 초대가 없습니다.", + acceptButton: "수락", + declineButton: "거절", + acceptSuccess: '"{tenant}"에 참여했습니다.', + declineSuccess: "초대를 거절했습니다.", + from: "초대자", + tenantLabel: "워크스페이스", + expiresIn: "만료: {date}", + messageLabel: "메시지", + gotoLink: "받은편지함 열기", + }, + errors: { + pendingExists: "이 사용자에 대한 대기 중인 초대가 이미 있습니다.", + alreadyMember: "이 사용자는 이미 멤버입니다.", + notPending: "초대가 더 이상 대기 상태가 아닙니다.", + expired: "초대가 만료되었습니다.", + forbidden: "초대 대상자만 수락 또는 거절할 수 있습니다.", + notFound: "초대를 찾을 수 없거나 이미 취소되었습니다.", + generic: "작업에 실패했습니다. 다시 시도해 주세요.", + }, + }, }; diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 0ed408ff..695c0c2d 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -4358,6 +4358,8 @@ export default { title: 'Участники', sectionDescription: 'Приглашайте коллег в тенант и управляйте их ролями. Добавлять и удалять участников может только Владелец.', totalCount: 'Участников: {n}', + listTitle: 'Участники пространства', + filterMatched: 'найдено: {n}', loading: 'Загрузка участников…', retry: 'Повторить', empty: 'Участников пока нет. Пригласите коллегу, чтобы начать.', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index e3cca744..e19fa4a1 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -4390,6 +4390,8 @@ export default { title: "成员管理", sectionDescription: "邀请伙伴加入当前空间并分配角色。只有 Owner 可以新增或移除成员。", totalCount: "共 {n} 位成员", + listTitle: "空间成员", + filterMatched: "筛选出 {n} 位", loading: "正在加载成员…", retry: "重试", empty: "尚未邀请任何成员。点击右上角邀请伙伴加入。", @@ -4486,6 +4488,11 @@ export default { "rbac.member_role_changed": "角色变更", "rbac.member_left": "成员退出", "rbac.access_denied": "访问被拒", + "rbac.invitation_sent": "发出邀请", + "rbac.invitation_accepted": "接受邀请", + "rbac.invitation_declined": "拒绝邀请", + "rbac.invitation_revoked": "撤销邀请", + "rbac.invitation_expired": "邀请过期", }, outcome: { success: "成功", @@ -4493,4 +4500,64 @@ export default { }, }, }, + tenantInvitation: { + inboxTooltip: "查看待接受的邀请", + pendingSectionTitle: "待接受的邀请", + pendingSectionCount: "{n} 条", + pendingSectionDesc: + "发出后等待对方在站内确认。{days} 天未响应将自动过期。", + pendingEmpty: "暂无待接受的邀请。", + inviteSubmit: "发送邀请", + inviteSuccess: "邀请已发出,等待对方接受。", + confirmInviteTitle: "确认发送邀请?", + confirmInviteBody: + "将向 {email} 发出加入邀请(角色:{role})。TA 在站内接受后才会成为成员。", + confirmSend: "发送", + revoke: { + button: "撤销", + confirmTitle: "确认撤销邀请?", + confirmBody: + "撤销后,{email} 将无法再接受此邀请;如需再邀请请重新发出。", + confirm: "撤销", + success: "邀请已撤销。", + }, + columns: { + invitee: "被邀请人", + role: "角色", + inviter: "邀请人", + expiresAt: "到期时间", + status: "状态", + operations: "操作", + }, + status: { + pending: "待接受", + accepted: "已接受", + declined: "已拒绝", + revoked: "已撤销", + expired: "已过期", + }, + myInbox: { + title: "我的邀请", + description: "其他空间发给您的加入邀请。接受后您将以对应角色加入对方空间。", + empty: "没有待处理的邀请。", + acceptButton: "接受", + declineButton: "拒绝", + acceptSuccess: '已加入 "{tenant}"。', + declineSuccess: "已拒绝邀请。", + from: "邀请人", + tenantLabel: "空间", + expiresIn: "到期:{date}", + messageLabel: "留言", + gotoLink: "进入收件箱", + }, + errors: { + pendingExists: "已经向该用户发出过一条待接受的邀请。", + alreadyMember: "该用户已是当前空间的成员。", + notPending: "邀请已不在待处理状态。", + expired: "邀请已过期。", + forbidden: "只有被邀请人本人可以接受或拒绝该邀请。", + notFound: "邀请不存在或已被撤销。", + generic: "操作失败,请稍后重试。", + }, + }, }; diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index e0e027ed..9f3d9fd9 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -34,6 +34,13 @@ export const useAuthStore = defineStore('auth', () => { // so PR 3 can render a tenant-switcher UI without a store migration. const memberships = ref>([]) 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(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 => { + try { + const { getCurrentUser } = await import('@/api/auth') + const response = await getCurrentUser() + const u = response.data?.user + if (!response.success || !u) return false + + setUser({ + id: u.id || '', + username: u.username || '', + email: u.email || '', + avatar: u.avatar, + tenant_id: String(u.tenant_id || response.data?.tenant?.id || ''), + can_access_all_tenants: u.can_access_all_tenants || false, + created_at: u.created_at || new Date().toISOString(), + updated_at: u.updated_at || new Date().toISOString(), + }) + + const tenantSnapshot = response.data?.tenant + if (tenantSnapshot) { + setTenant({ + id: String(tenantSnapshot.id) || '', + name: tenantSnapshot.name || '', + api_key: tenantSnapshot.api_key || '', + owner_id: tenantSnapshot.owner_id || u.id || '', + description: tenantSnapshot.description, + status: tenantSnapshot.status, + business: tenantSnapshot.business, + storage_quota: tenantSnapshot.storage_quota, + storage_used: tenantSnapshot.storage_used, + created_at: tenantSnapshot.created_at || new Date().toISOString(), + updated_at: tenantSnapshot.updated_at || new Date().toISOString(), + }) + } + + const list = response.data?.memberships + if (Array.isArray(list)) { + setMemberships(list) + } + + return true + } catch { + return false + } + } + const getSelectedTenant = () => { return selectedTenantId.value } @@ -265,6 +351,7 @@ export const useAuthStore = defineStore('auth', () => { selectedTenantName.value = null allTenants.value = [] memberships.value = [] + pendingInvitationCount.value = 0 // 清空localStorage localStorage.removeItem('weknora_user') @@ -381,6 +468,7 @@ export const useAuthStore = defineStore('auth', () => { selectedTenantName, allTenants, memberships, + pendingInvitationCount, // 计算属性 isLoggedIn, @@ -404,6 +492,9 @@ export const useAuthStore = defineStore('auth', () => { setSelectedTenant, setAllTenants, setMemberships, + setPendingInvitationCount, + fetchPendingInvitationCount, + refreshFromAuthMe, getSelectedTenant, setLiteMode, logout, diff --git a/frontend/src/views/settings/TenantInfo.vue b/frontend/src/views/settings/TenantInfo.vue index 979ff066..42a0400d 100644 --- a/frontend/src/views/settings/TenantInfo.vue +++ b/frontend/src/views/settings/TenantInfo.vue @@ -178,7 +178,7 @@ import { getCurrentUser, type TenantInfo } from '@/api/auth' import { updateTenant as updateTenantApi } from '@/api/tenant' import { leaveTenant, - listMembers, + fetchAllTenantMembers, type TenantMember, type TenantRole, } from '@/api/tenant/members' @@ -245,10 +245,7 @@ async function evaluateLeaveGate(): Promise { leaveGateLoading.value = true try { - const resp = await listMembers(infoId) - if (resp.success && resp.data?.members) { - leaveMembersSnap.value = resp.data.members - } + leaveMembersSnap.value = await fetchAllTenantMembers(infoId) } finally { leaveGateLoading.value = false leaveGateReady.value = true diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue index 4c16b047..c264e174 100644 --- a/frontend/src/views/settings/TenantMembers.vue +++ b/frontend/src/views/settings/TenantMembers.vue @@ -1,99 +1,235 @@