chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
import { get } from '@/utils/request'
// AuditAction mirrors internal/types/audit_log.go's namespaced action
// enum. The dot prefix (`rbac.`) is deliberate — future PRs will add
// `kb.*` / `agent.*` namespaces without a schema change, and the
// backend already treats this column as an opaque string. Keep this
// list in sync with types/audit_log.go.
export type AuditAction =
| 'rbac.member_added'
| 'rbac.member_removed'
| 'rbac.member_role_changed'
| 'rbac.member_left'
| 'rbac.access_denied'
| string // forward-compat: future namespaces shouldn't break the type
export type AuditOutcome = 'accepted' | 'success' | 'failed' | 'partial' | 'canceled' | 'denied'
// AuditLog mirrors internal/types/audit_log.go. `details` is the JSONB
// blob — for role changes it carries `{"old_role":..., "new_role":...}`,
// for access_denied it carries `{"required_role":...}`. We keep it as
// an opaque record so future detail shapes don't need a frontend
// breaking change.
export interface AuditLog {
id: number
tenant_id: number
actor_user_id: string
actor_role: string
action: AuditAction
scope_type: string
scope_id: string
target_type: string
target_id: string
target_user_id: string
request_path: string
request_method: string
outcome: AuditOutcome
details: Record<string, unknown> | string | null
created_at: string
}
export interface ListAuditLogResponse {
success: boolean
data?: AuditLog[]
next_cursor?: number
message?: string
}
export interface ListAuditLogParams {
// Cursor: rows with id < after_id, newest first. Pass the
// previous response's `next_cursor`. Omit on first page.
after_id?: number
// Page size, 1–100. Server defaults to 50 if omitted.
limit?: number
// Optional filters; backend matches on equality.
action?: AuditAction
outcome?: AuditOutcome
actor?: string
}
/**
* List the per-tenant audit log. Cursor-paginated by descending id.
* Backend: GET /api/v1/tenants/:id/audit-log (Admin+).
*
* The first call should pass no cursor. Each subsequent page should
* pass `after_id = previousResponse.next_cursor` until next_cursor
* comes back as 0 (no older rows).
*/
export async function listAuditLog(
tenantId: number,
params: ListAuditLogParams = {},
): Promise<ListAuditLogResponse> {
const qs = new URLSearchParams()
if (params.after_id) qs.append('after_id', String(params.after_id))
if (params.limit) qs.append('limit', String(params.limit))
if (params.action) qs.append('action', params.action)
if (params.outcome) qs.append('outcome', params.outcome)
if (params.actor) qs.append('actor', params.actor)
const tail = qs.toString()
const url = `/api/v1/tenants/${tenantId}/audit-log${tail ? '?' + tail : ''}`
return (await get(url)) as unknown as ListAuditLogResponse
}
+360
View File
@@ -0,0 +1,360 @@
import { del, get, post, put } from '@/utils/request'
import i18n from '@/i18n'
const t = (key: string) => i18n.global.t(key)
// 空间信息接口
export interface TenantInfo {
id: number
name: string
description?: string
status?: string
business?: string
storage_quota?: number
storage_used?: number
created_at: string
updated_at: string
}
export type APIPrincipalMode = 'tenant' | 'direct_header' | 'signed_token'
export interface APIPrincipalConfig {
mode: APIPrincipalMode
direct_header_name: string
signed_token_header_name: string
require_direct_header: boolean
// The server never returns the plaintext secret; only its presence.
has_hmac_secret: boolean
}
export interface UpdateAPIPrincipalConfigPayload {
mode: APIPrincipalMode
direct_header_name?: string
signed_token_header_name?: string
require_direct_header?: boolean
hmac_secret?: string
}
export interface CreateAPIPrincipalTestTokenPayload {
external_user_id: string
expires_in_seconds?: number
}
export interface APIPrincipalTestToken {
token: string
header_name: string
expires_in_seconds: number
expires_at_unix: number
external_user_id: string
}
// Bounded per-key grants for non-full-access API keys.
// - 'retrieve': read/search knowledge-base data within scope
// - 'chat': run the conversation flow (sessions + agent listing + self identity)
// - 'read_agents': list/read agents without chat or authoring
// - 'ingest': write content into allowed knowledge bases (docs/chunks/FAQ/tags/wiki)
// - 'manage_kbs': manage the KB lifecycle (create/copy/duplicate/update/delete + config)
// - 'manage_agents': create/update/delete/copy agents
// - 'message_history': search/read tenant chat-history metadata
// - 'manage_models': manage tenant model definitions, checks, and credentials
// - 'manage_mcp_services': manage MCP services, credentials, tool policies, and OAuth state
// - 'manage_datasources': manage data-source connectors and sync jobs
// - 'manage_channels': manage embed and IM channels
// - 'manage_vector_stores': manage vector stores and parser/storage checks
// - 'manage_web_search': manage web-search providers
// - 'run_evaluations': run/read evaluation jobs
// - 'manage_members': manage tenant members and invitations
// - 'manage_spaces': manage organization/space collaboration
// - 'manage_tenant_settings': read/update tenant integration settings (API principal mode, headers, tenant KV)
export type TenantAPIKeyCapability =
| 'retrieve'
| 'chat'
| 'read_agents'
| 'ingest'
| 'manage_kbs'
| 'manage_agents'
| 'message_history'
| 'manage_models'
| 'manage_mcp_services'
| 'manage_datasources'
| 'manage_channels'
| 'manage_vector_stores'
| 'manage_storage_backends'
| 'manage_web_search'
| 'run_evaluations'
| 'manage_members'
| 'manage_spaces'
| 'manage_tenant_settings'
| 'system_tenants_read'
| 'system_tenants_manage'
| 'system_settings_read'
| 'system_settings_manage'
| 'system_runtime_read'
| 'system_runtime_manage'
| 'system_audit_read'
export interface TenantAPIKey {
id: number
scope_type?: 'tenant' | 'platform'
name: string
api_key: string
full_access: boolean
knowledge_base_ids: string[] | null
capabilities?: TenantAPIKeyCapability[]
last_used_at?: string
expires_at?: string
created_at: string
}
export interface CreatedTenantAPIKey extends TenantAPIKey {
token?: string
}
export interface CreateTenantAPIKeyPayload {
name: string
full_access?: boolean
knowledge_base_ids?: string[]
capabilities?: TenantAPIKeyCapability[]
expires_at_unix?: number
}
export interface UpdateTenantAPIKeyPayload {
name: string
full_access: boolean
knowledge_base_ids: string[]
capabilities: TenantAPIKeyCapability[]
expires_at_unix?: number
}
// 搜索空间参数
export interface SearchTenantsParams {
keyword?: string
tenant_id?: number
page?: number
page_size?: number
}
// 搜索空间响应
export interface SearchTenantsResponse {
success: boolean
data?: {
items: TenantInfo[]
total: number
page: number
page_size: number
}
message?: string
}
/**
* 获取所有空间列表(需要跨空间访问权限)
* @deprecated 建议使用 searchTenants 代替,支持分页和搜索
*/
export async function listAllTenants(): Promise<{ success: boolean; data?: { items: TenantInfo[] }; message?: string }> {
try {
const response = await get('/api/v1/tenants/all')
return response as unknown as { success: boolean; data?: { items: TenantInfo[] }; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.listFailed')
}
}
}
export async function getAPIPrincipalConfig(
tenantId: number,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await get(`/api/v1/tenants/${tenantId}/api-principal-config`)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.getApiPrincipalConfigFailed'),
}
}
}
export async function updateAPIPrincipalConfig(
tenantId: number,
payload: UpdateAPIPrincipalConfigPayload,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await put(`/api/v1/tenants/${tenantId}/api-principal-config`, payload)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.updateApiPrincipalConfigFailed'),
}
}
}
export async function createAPIPrincipalTestToken(
tenantId: number,
payload: CreateAPIPrincipalTestTokenPayload,
): Promise<{ success: boolean; data?: APIPrincipalTestToken; message?: string }> {
try {
const response = await post(`/api/v1/tenants/${tenantId}/api-principal-test-token`, payload)
return response as unknown as { success: boolean; data?: APIPrincipalTestToken; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.createApiPrincipalTestTokenFailed'),
}
}
}
export async function listTenantAPIKeys(
tenantId: number,
): Promise<{ success: boolean; data?: TenantAPIKey[]; message?: string }> {
try {
const response = await get(`/api/v1/tenants/${tenantId}/api-keys`)
return response as unknown as { success: boolean; data?: TenantAPIKey[]; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.listApiKeysFailed'),
}
}
}
export async function createTenantAPIKey(
tenantId: number,
payload: CreateTenantAPIKeyPayload,
): Promise<{ success: boolean; data?: CreatedTenantAPIKey; message?: string }> {
try {
const response = await post(`/api/v1/tenants/${tenantId}/api-keys`, payload)
return response as unknown as { success: boolean; data?: CreatedTenantAPIKey; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.createApiKeyFailed'),
}
}
}
/** 更新已创建租户 API Key 的授权范围和其他可配置属性。 */
export async function updateTenantAPIKey(
tenantId: number,
keyId: number,
payload: UpdateTenantAPIKeyPayload,
): Promise<{ success: boolean; data?: TenantAPIKey; message?: string }> {
try {
const response = await put(`/api/v1/tenants/${tenantId}/api-keys/${keyId}`, payload)
return response as unknown as { success: boolean; data?: TenantAPIKey; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('integrations.api.updateApiKeyScopeFailed'),
}
}
}
export async function deleteTenantAPIKey(
tenantId: number,
keyId: number,
): Promise<{ success: boolean; message?: string }> {
try {
const response = await del(`/api/v1/tenants/${tenantId}/api-keys/${keyId}`)
return response as unknown as { success: boolean; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.deleteApiKeyFailed'),
}
}
}
/**
* 更新空间信息(目前暴露名称、描述两个字段的编辑入口)。
* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会
* 被改动;这里也按需选择性传 `name` / `description`,互不影响。
* 权限:owner(与 router.go 中的 g.Owner() 守卫保持一致)。
*/
export async function updateTenant(
tenantId: number,
payload: { name?: string; description?: string },
): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
try {
const response = await put(`/api/v1/tenants/${tenantId}`, payload)
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.updateFailed'),
}
}
}
/**
* 删除当前工作区。权限:owner。
*/
export async function deleteTenant(
tenantId: number,
): Promise<{ success: boolean; message?: string }> {
try {
const response = await del(`/api/v1/tenants/${tenantId}`)
return response as unknown as { success: boolean; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.deleteFailed'),
}
}
}
/**
* 创建新工作区(任意已登录用户均可调用)。
* 后端会自动把调用者写成新空间的 Owner,并填充默认 storage_quota
* 等服务端字段;API Key 由用户在集成页手动创建。
* 路由:POST /api/v1/tenants(router 上不挂 g.CrossTenant(),自助场景使用)。
*/
export async function createTenant(
payload: { name: string; description?: string },
): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
try {
const response = await post('/api/v1/tenants', payload)
return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
} catch (error: any) {
const code = error?.error?.code ?? error?.code
return {
success: false,
message: code === 2005
? t('tenant.create.disabled')
: (error.message || t('error.tenant.createFailed')),
}
}
}
/**
* 搜索空间(支持分页、关键词搜索和空间ID过滤)
*/
export async function searchTenants(params: SearchTenantsParams = {}): Promise<SearchTenantsResponse> {
try {
const queryParams = new URLSearchParams()
if (params.keyword) {
queryParams.append('keyword', params.keyword)
}
if (params.tenant_id) {
queryParams.append('tenant_id', String(params.tenant_id))
}
if (params.page) {
queryParams.append('page', String(params.page))
}
if (params.page_size) {
queryParams.append('page_size', String(params.page_size))
}
const queryString = queryParams.toString()
const url = `/api/v1/tenants/search${queryString ? '?' + queryString : ''}`
const response = await get(url)
return response as unknown as SearchTenantsResponse
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.searchFailed')
}
}
}
+267
View File
@@ -0,0 +1,267 @@
import { get, post, del } from '@/utils/request'
import type { TenantMember, 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
// invite_url is set on share-link rows that are still pending. The
// backend re-emits it on every list/get so Owners can copy the
// link on demand without "copy now or revoke" pressure.
invite_url?: string
// is_share_link distinguishes share-link rows (no specific invitee,
// multi-use, copyable URL) from per-user invitations.
is_share_link?: boolean
// accepted_count counts how many users have completed registration
// through this invitation. Surfaced in the management UI for
// share-link rows ("已加入 N 人").
accepted_count?: number
}
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
// With tenant.auto_accept_invitation enabled the backend returns a
// TenantMember (user_id set) instead of a pending TenantInvitation.
data?: TenantInvitation | TenantMember
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
}
// AcceptInvitationByTokenResponse:已登录用户用 token 加入空间的响应(tenant_name 供前端展示)。
export interface AcceptInvitationByTokenResponse {
success: boolean
data?: {
membership: {
tenant_id: number
role: TenantRole
status: string
joined_at: string
}
tenant_name?: 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
}
/**
* 已登录用户用共享链接 token 加入空间(需鉴权,不创建新账号)。
* 用于 invite_only 模式下的邀请链接流程:链接导向登录而非注册,登录后再兑换 token。
* Backend: POST /api/v1/me/invitations/accept-by-token (authenticated).
*/
export async function acceptInvitationByToken(
token: string,
): Promise<AcceptInvitationByTokenResponse> {
return (await post(
`/api/v1/me/invitations/accept-by-token`,
{ token },
)) as unknown as AcceptInvitationByTokenResponse
}
/**
* 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
}
// ---- share-link API ----------------------------------------------------
export interface CreateInviteLinkRequest {
role: TenantRole
message?: string
}
export interface CreateInviteLinkResponse {
success: boolean
data?: TenantInvitation
message?: string
}
/**
* Generate a multi-use share-link invitation for the tenant. The
* returned row carries `invite_url` (composed from the persisted
* plaintext token) which the SPA copies into clipboards. The link
* stays valid until expiry or revocation; revoking is the same DELETE
* as a per-user invitation.
*
* Backend: POST /api/v1/tenants/:id/invite-links (Owner+).
*/
export async function createInviteLink(
tenantId: number,
body: CreateInviteLinkRequest,
): Promise<CreateInviteLinkResponse> {
return (await post(
`/api/v1/tenants/${tenantId}/invite-links`,
body,
)) as unknown as CreateInviteLinkResponse
}
+155
View File
@@ -0,0 +1,155 @@
import { get, post, put, del } from '@/utils/request'
// TenantRole mirrors internal/types/tenant_member.go's four-role enum.
// Keep the string values aligned with the Go constants.
export type TenantRole = 'owner' | 'admin' | 'contributor' | 'viewer'
export type TenantMemberStatus = 'active' | 'invited' | 'suspended'
// TenantMember is the API projection of a (user, tenant) membership row,
// already joined with the user's email/username/avatar by the backend.
export interface TenantMember {
user_id: string
email: string
username: string
/** 姓名:来自 OIDC 可配置 claim(默认 nickname),本地/工号账号可能为空 */
display_name?: string
avatar?: string
role: TenantRole
status: TenantMemberStatus
invited_by?: string | null
joined_at: string
}
export interface ListMembersResponse {
success: boolean
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
}
export interface AddMemberResponse {
success: boolean
data?: TenantMember
message?: string
}
export interface SimpleResponse {
success: boolean
message?: string
}
/**
* 分页列出空间成员。
* Backend: GET /api/v1/tenants/:id/members (Viewer+)。查询参数:`q`、`page`、`page_size`。
*/
export async function listMembers(
tenantId: number,
params: ListMembersParams = {},
): Promise<ListMembersResponse> {
const qs = buildMembersQuery(params)
return (await get(
`/api/v1/tenants/${tenantId}/members${qs}`,
)) as unknown as ListMembersResponse
}
/**
* 遍历分页拉取空间的全部成员(每页最大 100,最多 500 页兜底)。
* 用于「退出空间」等对全量成员的轻量校验;普通表格请直接使用 {@link listMembers} 分页接口。
*/
export async function 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
}
/**
* Invite an existing user (by email) to the tenant with the given role.
* Backend: POST /api/v1/tenants/:id/members (Owner+).
*
* Returns 404 when the email does not match any registered user — the
* caller should ask the invitee to register first. PR 3 does not yet
* support email-based invites for users who don't have an account.
*/
export async function addMember(
tenantId: number,
body: AddMemberRequest,
): Promise<AddMemberResponse> {
return (await post(`/api/v1/tenants/${tenantId}/members`, body)) as unknown as AddMemberResponse
}
/**
* Change an existing member's role.
* Backend: PUT /api/v1/tenants/:id/members/:user_id (Owner+).
*
* Returns 409 when this would demote the last active Owner of the tenant.
*/
export async function updateMemberRole(
tenantId: number,
userId: string,
role: TenantRole,
): Promise<SimpleResponse> {
return (await put(`/api/v1/tenants/${tenantId}/members/${userId}`, { role })) as unknown as SimpleResponse
}
/**
* Remove a member from the tenant.
* Backend: DELETE /api/v1/tenants/:id/members/:user_id (Owner+).
*
* Returns 409 when this would remove the last active Owner.
*/
export async function removeMember(
tenantId: number,
userId: string,
): Promise<SimpleResponse> {
return (await del(`/api/v1/tenants/${tenantId}/members/${userId}`)) as unknown as SimpleResponse
}
/**
* Quit the tenant on your own. Same last-Owner invariant as
* removeMember, but does NOT require Owner+ — any active member can
* call it.
* Backend: POST /api/v1/tenants/:id/leave (Viewer+).
*/
export async function leaveTenant(tenantId: number): Promise<SimpleResponse> {
return (await post(`/api/v1/tenants/${tenantId}/leave`)) as unknown as SimpleResponse
}