feat(organization): implement searchable organizations feature
- Added a 'searchable' flag to organizations, allowing them to be discoverable and joinable by ID without an invite code. - Introduced API endpoints for searching and joining searchable organizations. - Updated UI components to support searching for organizations and displaying results. - Enhanced localization for new search-related features in both English and Chinese. This update improves user experience by enabling easier discovery and joining of organizations.
This commit is contained in:
@@ -11,6 +11,7 @@ export interface Organization {
|
|||||||
invite_code_expires_at?: string | null
|
invite_code_expires_at?: string | null
|
||||||
invite_code_validity_days?: number
|
invite_code_validity_days?: number
|
||||||
require_approval?: boolean
|
require_approval?: boolean
|
||||||
|
searchable?: boolean
|
||||||
member_count?: number
|
member_count?: number
|
||||||
share_count?: number
|
share_count?: number
|
||||||
pending_join_request_count?: number
|
pending_join_request_count?: number
|
||||||
@@ -82,6 +83,18 @@ export interface OrganizationPreview {
|
|||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Searchable (discoverable) organization item for join flow */
|
||||||
|
export interface SearchableOrganizationItem {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
avatar?: string
|
||||||
|
member_count: number
|
||||||
|
share_count: number
|
||||||
|
is_already_member: boolean
|
||||||
|
require_approval: boolean
|
||||||
|
}
|
||||||
|
|
||||||
// Request types
|
// Request types
|
||||||
export interface CreateOrganizationRequest {
|
export interface CreateOrganizationRequest {
|
||||||
name: string
|
name: string
|
||||||
@@ -95,6 +108,7 @@ export interface UpdateOrganizationRequest {
|
|||||||
description?: string
|
description?: string
|
||||||
avatar?: string
|
avatar?: string
|
||||||
require_approval?: boolean
|
require_approval?: boolean
|
||||||
|
searchable?: boolean
|
||||||
invite_code_validity_days?: number // 0=never, 1, 7, 30
|
invite_code_validity_days?: number // 0=never, 1, 7, 30
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,6 +298,48 @@ export async function previewOrganization(inviteCode: string): Promise<ApiRespon
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search searchable (discoverable) organizations
|
||||||
|
*/
|
||||||
|
export async function searchSearchableOrganizations(
|
||||||
|
q: string = '',
|
||||||
|
limit: number = 20
|
||||||
|
): Promise<ApiResponse<{ data: SearchableOrganizationItem[]; total: number }>> {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (q) params.set('q', q)
|
||||||
|
params.set('limit', String(limit))
|
||||||
|
const response = await get(`/api/v1/organizations/search?${params.toString()}`)
|
||||||
|
const res = response as unknown as { success: boolean; data?: SearchableOrganizationItem[]; total?: number; message?: string }
|
||||||
|
return {
|
||||||
|
success: res.success,
|
||||||
|
data: res.success ? { data: res.data || [], total: res.total ?? 0 } : undefined,
|
||||||
|
message: res.message,
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
return { success: false, message: error.message || 'Failed to search organizations' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Join a searchable organization by ID (no invite code)
|
||||||
|
*/
|
||||||
|
export async function joinOrganizationById(
|
||||||
|
organizationId: string,
|
||||||
|
message?: string,
|
||||||
|
role?: 'admin' | 'editor' | 'viewer'
|
||||||
|
): Promise<ApiResponse<Organization>> {
|
||||||
|
try {
|
||||||
|
const body: { organization_id: string; message?: string; role?: string } = { organization_id: organizationId }
|
||||||
|
if (message) body.message = message
|
||||||
|
if (role) body.role = role
|
||||||
|
const response = await post('/api/v1/organizations/join-by-id', body)
|
||||||
|
return response as unknown as ApiResponse<Organization>
|
||||||
|
} catch (error: any) {
|
||||||
|
return { success: false, message: error.message || 'Failed to join organization' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Leave organization
|
* Leave organization
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2370,6 +2370,12 @@ export default {
|
|||||||
shareCount: '{count} shared knowledge bases',
|
shareCount: '{count} shared knowledge bases',
|
||||||
alreadyMember: 'You are already a member of this space',
|
alreadyMember: 'You are already a member of this space',
|
||||||
invalidCode: 'Invalid invite code',
|
invalidCode: 'Invalid invite code',
|
||||||
|
byInviteCode: 'Enter invite code',
|
||||||
|
searchSpaces: 'Search spaces',
|
||||||
|
searchSpacesDesc: 'Browse or search spaces that are open for discovery; join without an invite code',
|
||||||
|
searchSpacesPlaceholder: 'Search by space name or description',
|
||||||
|
noSearchResult: 'No matching spaces',
|
||||||
|
noSearchableSpaces: 'No discoverable spaces yet, or try a search',
|
||||||
},
|
},
|
||||||
invite: {
|
invite: {
|
||||||
loading: 'Loading...',
|
loading: 'Loading...',
|
||||||
@@ -2394,6 +2400,7 @@ export default {
|
|||||||
requestRole: 'Requested role',
|
requestRole: 'Requested role',
|
||||||
selectRole: 'Select role',
|
selectRole: 'Select role',
|
||||||
messagePlaceholder: 'Optional: message (e.g. intro or reason to join)',
|
messagePlaceholder: 'Optional: message (e.g. intro or reason to join)',
|
||||||
|
applicationNote: 'Application note (optional)',
|
||||||
joinSuccess: 'Successfully joined space!',
|
joinSuccess: 'Successfully joined space!',
|
||||||
joinFailed: 'Failed to join, please try again',
|
joinFailed: 'Failed to join, please try again',
|
||||||
requestSubmitted: 'Request submitted, please wait for admin approval',
|
requestSubmitted: 'Request submitted, please wait for admin approval',
|
||||||
@@ -2473,6 +2480,8 @@ export default {
|
|||||||
removeShareFailed: 'Failed to remove, please try again',
|
removeShareFailed: 'Failed to remove, please try again',
|
||||||
requireApproval: 'Require Approval',
|
requireApproval: 'Require Approval',
|
||||||
requireApprovalDesc: 'When enabled, new members need admin approval to join',
|
requireApprovalDesc: 'When enabled, new members need admin approval to join',
|
||||||
|
searchable: 'Open for search',
|
||||||
|
searchableDesc: 'When enabled, this space appears in the "Join Space" search list; others can search and request to join without an invite code',
|
||||||
joinRequests: 'Join Requests',
|
joinRequests: 'Join Requests',
|
||||||
joinRequestsDesc: 'Review pending requests to join the space',
|
joinRequestsDesc: 'Review pending requests to join the space',
|
||||||
noPendingRequests: 'No pending requests',
|
noPendingRequests: 'No pending requests',
|
||||||
|
|||||||
@@ -2375,6 +2375,12 @@ export default {
|
|||||||
shareCount: "{count} 个共享知识库",
|
shareCount: "{count} 个共享知识库",
|
||||||
alreadyMember: "您已经是该空间的成员",
|
alreadyMember: "您已经是该空间的成员",
|
||||||
invalidCode: "无效的邀请码",
|
invalidCode: "无效的邀请码",
|
||||||
|
byInviteCode: "输入邀请码",
|
||||||
|
searchSpaces: "搜索空间",
|
||||||
|
searchSpacesDesc: "浏览或搜索已开放可被搜索的空间,无需邀请码即可加入",
|
||||||
|
searchSpacesPlaceholder: "按空间名称或描述搜索",
|
||||||
|
noSearchResult: "未找到匹配的空间",
|
||||||
|
noSearchableSpaces: "暂无开放可被搜索的空间,或输入关键词搜索",
|
||||||
},
|
},
|
||||||
invite: {
|
invite: {
|
||||||
loading: "加载中...",
|
loading: "加载中...",
|
||||||
@@ -2399,6 +2405,7 @@ export default {
|
|||||||
requestRole: "申请角色",
|
requestRole: "申请角色",
|
||||||
selectRole: "选择角色",
|
selectRole: "选择角色",
|
||||||
messagePlaceholder: "选填:申请说明(如自我介绍或加入原因)",
|
messagePlaceholder: "选填:申请说明(如自我介绍或加入原因)",
|
||||||
|
applicationNote: "申请说明(选填)",
|
||||||
joinSuccess: "成功加入空间!",
|
joinSuccess: "成功加入空间!",
|
||||||
joinFailed: "加入失败,请稍后重试",
|
joinFailed: "加入失败,请稍后重试",
|
||||||
requestSubmitted: "申请已提交,请等待管理员审核",
|
requestSubmitted: "申请已提交,请等待管理员审核",
|
||||||
@@ -2478,6 +2485,8 @@ export default {
|
|||||||
removeShareFailed: "移除失败,请重试",
|
removeShareFailed: "移除失败,请重试",
|
||||||
requireApproval: "需要审核",
|
requireApproval: "需要审核",
|
||||||
requireApprovalDesc: "开启后,新成员加入需要管理员审核",
|
requireApprovalDesc: "开启后,新成员加入需要管理员审核",
|
||||||
|
searchable: "开放可被搜索",
|
||||||
|
searchableDesc: "开启后,空间将出现在「加入空间」的搜索列表中,他人可搜索并申请加入,无需邀请码",
|
||||||
joinRequests: "加入申请",
|
joinRequests: "加入申请",
|
||||||
joinRequestsDesc: "审核待加入空间的申请",
|
joinRequestsDesc: "审核待加入空间的申请",
|
||||||
noPendingRequests: "暂无待审核的申请",
|
noPendingRequests: "暂无待审核的申请",
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -162,6 +162,23 @@
|
|||||||
<span class="approval-desc">{{ $t('organization.settings.requireApprovalDesc') }}</span>
|
<span class="approval-desc">{{ $t('organization.settings.requireApprovalDesc') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="invite-divider"></div>
|
||||||
|
|
||||||
|
<!-- 开放可被搜索 -->
|
||||||
|
<div class="invite-method">
|
||||||
|
<div class="invite-method-header">
|
||||||
|
<t-icon name="search" class="invite-icon" />
|
||||||
|
<span class="invite-method-title">{{ $t('organization.settings.searchable') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="approval-toggle">
|
||||||
|
<t-switch
|
||||||
|
v-model="formData.searchable"
|
||||||
|
@change="handleSearchableToggle"
|
||||||
|
/>
|
||||||
|
<span class="approval-desc">{{ $t('organization.settings.searchableDesc') }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -655,6 +672,7 @@ const formData = ref({
|
|||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
require_approval: false,
|
require_approval: false,
|
||||||
|
searchable: false,
|
||||||
invite_code_validity_days: 7 as number
|
invite_code_validity_days: 7 as number
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -780,6 +798,7 @@ const fetchOrgDetail = async () => {
|
|||||||
name: res.data.name,
|
name: res.data.name,
|
||||||
description: res.data.description || '',
|
description: res.data.description || '',
|
||||||
require_approval: res.data.require_approval || false,
|
require_approval: res.data.require_approval || false,
|
||||||
|
searchable: res.data.searchable || false,
|
||||||
invite_code_validity_days: typeof validity === 'number' ? validity : 7
|
invite_code_validity_days: typeof validity === 'number' ? validity : 7
|
||||||
}
|
}
|
||||||
inviteCode.value = res.data.invite_code || ''
|
inviteCode.value = res.data.invite_code || ''
|
||||||
@@ -929,6 +948,7 @@ const handleSave = async () => {
|
|||||||
name: formData.value.name.trim(),
|
name: formData.value.name.trim(),
|
||||||
description: formData.value.description.trim(),
|
description: formData.value.description.trim(),
|
||||||
require_approval: formData.value.require_approval,
|
require_approval: formData.value.require_approval,
|
||||||
|
searchable: formData.value.searchable,
|
||||||
invite_code_validity_days: formData.value.invite_code_validity_days
|
invite_code_validity_days: formData.value.invite_code_validity_days
|
||||||
})
|
})
|
||||||
if (res.success) {
|
if (res.success) {
|
||||||
@@ -1139,6 +1159,25 @@ const handleApprovalToggle = async (value: boolean) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 切换开放可被搜索时立即保存
|
||||||
|
const handleSearchableToggle = async (value: boolean) => {
|
||||||
|
if (!props.orgId) return
|
||||||
|
try {
|
||||||
|
const res = await updateOrganization(props.orgId, {
|
||||||
|
searchable: value
|
||||||
|
})
|
||||||
|
if (res.success) {
|
||||||
|
MessagePlugin.success(t('common.saveSuccess'))
|
||||||
|
} else {
|
||||||
|
formData.value.searchable = !value
|
||||||
|
MessagePlugin.error(res.message || t('common.saveFailed'))
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
formData.value.searchable = !value
|
||||||
|
MessagePlugin.error(error?.message || t('common.saveFailed'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handleShareClick = (share: KnowledgeBaseShare) => {
|
const handleShareClick = (share: KnowledgeBaseShare) => {
|
||||||
handleClose()
|
handleClose()
|
||||||
router.push(`/platform/knowledge-bases/${share.knowledge_base_id}`)
|
router.push(`/platform/knowledge-bases/${share.knowledge_base_id}`)
|
||||||
@@ -1194,7 +1233,7 @@ watch(() => props.visible, (newVal) => {
|
|||||||
joinRequests.value = []
|
joinRequests.value = []
|
||||||
if (props.mode === 'create') {
|
if (props.mode === 'create') {
|
||||||
// 创建模式:重置表单
|
// 创建模式:重置表单
|
||||||
formData.value = { name: '', description: '', require_approval: false, invite_code_validity_days: 7 }
|
formData.value = { name: '', description: '', require_approval: false, searchable: false, invite_code_validity_days: 7 }
|
||||||
orgInfo.value = null
|
orgInfo.value = null
|
||||||
members.value = []
|
members.value = []
|
||||||
sharedKnowledgeBases.value = []
|
sharedKnowledgeBases.value = []
|
||||||
|
|||||||
@@ -77,10 +77,28 @@ func (r *organizationRepository) ListByUserID(ctx context.Context, userID string
|
|||||||
return orgs, nil
|
return orgs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListSearchable lists organizations that are searchable (open for discovery), optionally filtered by name/description
|
||||||
|
func (r *organizationRepository) ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
var orgs []*types.Organization
|
||||||
|
q := r.db.WithContext(ctx).Where("searchable = ?", true)
|
||||||
|
if query != "" {
|
||||||
|
pattern := "%" + query + "%"
|
||||||
|
q = q.Where("name ILIKE ? OR description ILIKE ?", pattern, pattern)
|
||||||
|
}
|
||||||
|
err := q.Order("created_at DESC").Limit(limit).Find(&orgs).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return orgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Update updates an organization (Select ensures zero values like invite_code_validity_days=0 are persisted)
|
// Update updates an organization (Select ensures zero values like invite_code_validity_days=0 are persisted)
|
||||||
func (r *organizationRepository) Update(ctx context.Context, org *types.Organization) error {
|
func (r *organizationRepository) Update(ctx context.Context, org *types.Organization) error {
|
||||||
return r.db.WithContext(ctx).Model(&types.Organization{}).Where("id = ?", org.ID).
|
return r.db.WithContext(ctx).Model(&types.Organization{}).Where("id = ?", org.ID).
|
||||||
Select("name", "description", "require_approval", "invite_code_validity_days", "updated_at").
|
Select("name", "description", "require_approval", "searchable", "invite_code_validity_days", "updated_at").
|
||||||
Updates(org).Error
|
Updates(org).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -170,6 +170,9 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
|
|||||||
if req.RequireApproval != nil {
|
if req.RequireApproval != nil {
|
||||||
org.RequireApproval = *req.RequireApproval
|
org.RequireApproval = *req.RequireApproval
|
||||||
}
|
}
|
||||||
|
if req.Searchable != nil {
|
||||||
|
org.Searchable = *req.Searchable
|
||||||
|
}
|
||||||
if req.InviteCodeValidityDays != nil {
|
if req.InviteCodeValidityDays != nil {
|
||||||
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
||||||
return nil, ErrInvalidValidityDays
|
return nil, ErrInvalidValidityDays
|
||||||
@@ -185,6 +188,85 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
|
|||||||
return org, nil
|
return org, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SearchSearchableOrganizations returns searchable (discoverable) organizations for the current user
|
||||||
|
func (s *organizationService) SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
orgs, err := s.orgRepo.ListSearchable(ctx, query, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
memberCounts := make(map[string]int64)
|
||||||
|
shareCounts := make(map[string]int64)
|
||||||
|
memberOrgIDs := make(map[string]bool)
|
||||||
|
for _, org := range orgs {
|
||||||
|
if mc, err := s.orgRepo.CountMembers(ctx, org.ID); err == nil {
|
||||||
|
memberCounts[org.ID] = mc
|
||||||
|
}
|
||||||
|
shares, _ := s.shareRepo.ListByOrganization(ctx, org.ID)
|
||||||
|
shareCounts[org.ID] = int64(len(shares))
|
||||||
|
_, err := s.orgRepo.GetMember(ctx, org.ID, userID)
|
||||||
|
memberOrgIDs[org.ID] = (err == nil)
|
||||||
|
}
|
||||||
|
items := make([]types.SearchableOrganizationItem, 0, len(orgs))
|
||||||
|
for _, org := range orgs {
|
||||||
|
items = append(items, types.SearchableOrganizationItem{
|
||||||
|
ID: org.ID,
|
||||||
|
Name: org.Name,
|
||||||
|
Description: org.Description,
|
||||||
|
Avatar: org.Avatar,
|
||||||
|
MemberCount: int(memberCounts[org.ID]),
|
||||||
|
ShareCount: int(shareCounts[org.ID]),
|
||||||
|
IsAlreadyMember: memberOrgIDs[org.ID],
|
||||||
|
RequireApproval: org.RequireApproval,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return &types.ListSearchableOrganizationsResponse{
|
||||||
|
Organizations: items,
|
||||||
|
Total: int64(len(items)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinByOrganizationID joins a searchable organization by ID (no invite code required)
|
||||||
|
func (s *organizationService) JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error) {
|
||||||
|
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||||
|
return nil, ErrOrgNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !org.Searchable {
|
||||||
|
return nil, ErrOrgPermissionDenied // or a dedicated "org not discoverable" error
|
||||||
|
}
|
||||||
|
_, err = s.orgRepo.GetMember(ctx, orgID, userID)
|
||||||
|
if err == nil {
|
||||||
|
return org, nil // already member
|
||||||
|
}
|
||||||
|
// Validate requested role if provided
|
||||||
|
if requestedRole != "" && !requestedRole.IsValid() {
|
||||||
|
return nil, ErrInvalidRole
|
||||||
|
}
|
||||||
|
// Default to viewer if not specified
|
||||||
|
if requestedRole == "" {
|
||||||
|
requestedRole = types.OrgRoleViewer
|
||||||
|
}
|
||||||
|
if org.RequireApproval {
|
||||||
|
_, err = s.SubmitJoinRequest(ctx, orgID, userID, tenantID, message, requestedRole)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return org, nil
|
||||||
|
}
|
||||||
|
// Direct join using invite code flow logic (add member)
|
||||||
|
_, err = s.JoinByInviteCode(ctx, org.InviteCode, userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return org, nil
|
||||||
|
}
|
||||||
|
|
||||||
// DeleteOrganization deletes an organization
|
// DeleteOrganization deletes an organization
|
||||||
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error {
|
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error {
|
||||||
org, err := s.orgRepo.GetByID(ctx, id)
|
org, err := s.orgRepo.GetByID(ctx, id)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
@@ -514,6 +515,90 @@ func (h *OrganizationHandler) SubmitJoinRequest(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SearchOrganizations returns searchable (discoverable) organizations
|
||||||
|
// @Summary 搜索可加入的空间
|
||||||
|
// @Description 搜索已开放可被搜索的空间,用于发现并加入
|
||||||
|
// @Tags 组织管理
|
||||||
|
// @Produce json
|
||||||
|
// @Param q query string false "搜索关键词(空间名称或描述)"
|
||||||
|
// @Param limit query int false "返回数量限制" default(20)
|
||||||
|
// @Success 200 {object} map[string]interface{}
|
||||||
|
// @Security Bearer
|
||||||
|
// @Router /organizations/search [get]
|
||||||
|
func (h *OrganizationHandler) SearchOrganizations(c *gin.Context) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
userID, _ := c.Get(types.UserIDContextKey.String())
|
||||||
|
query := c.Query("q")
|
||||||
|
limit := 20
|
||||||
|
if l := c.Query("limit"); l != "" {
|
||||||
|
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 100 {
|
||||||
|
limit = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resp, err := h.orgService.SearchSearchableOrganizations(ctx, userID.(string), query, limit)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorf(ctx, "Failed to search organizations: %v", err)
|
||||||
|
c.Error(apperrors.NewInternalServerError("Failed to search organizations"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"data": resp.Organizations,
|
||||||
|
"total": resp.Total,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinByOrganizationID joins a searchable organization by ID (no invite code)
|
||||||
|
// @Summary 通过空间 ID 加入(可搜索空间)
|
||||||
|
// @Description 加入已开放可被搜索的空间,无需邀请码
|
||||||
|
// @Tags 组织管理
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param request body types.JoinByOrganizationIDRequest true "空间 ID"
|
||||||
|
// @Success 200 {object} map[string]interface{}
|
||||||
|
// @Failure 403 {object} errors.AppError
|
||||||
|
// @Security Bearer
|
||||||
|
// @Router /organizations/join-by-id [post]
|
||||||
|
func (h *OrganizationHandler) JoinByOrganizationID(c *gin.Context) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
userID, _ := c.Get(types.UserIDContextKey.String())
|
||||||
|
tenantID, _ := c.Get(types.TenantIDContextKey.String())
|
||||||
|
var req types.JoinByOrganizationIDRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.Error(apperrors.NewValidationError("Invalid request parameters").WithDetails(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Validate requested role if provided
|
||||||
|
requestedRole := req.Role
|
||||||
|
if requestedRole != "" && !requestedRole.IsValid() {
|
||||||
|
c.Error(apperrors.NewValidationError("Invalid role; must be viewer, editor, or admin"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
org, err := h.orgService.JoinByOrganizationID(ctx, req.OrganizationID, userID.(string), tenantID.(uint64), req.Message, requestedRole)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorf(ctx, "Failed to join organization by ID: %v", err)
|
||||||
|
if errors.Is(err, service.ErrOrgNotFound) {
|
||||||
|
c.Error(apperrors.NewNotFoundError("Organization not found or not open for search"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if errors.Is(err, service.ErrOrgPermissionDenied) {
|
||||||
|
c.Error(apperrors.NewForbiddenError("Organization not open for search"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if errors.Is(err, service.ErrInvalidRole) {
|
||||||
|
c.Error(apperrors.NewValidationError("Invalid role"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Error(apperrors.NewInternalServerError("Failed to join organization"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logger.Infof(ctx, "User %s joined organization %s by ID", secutils.SanitizeForLog(userID.(string)), org.ID)
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"success": true,
|
||||||
|
"data": h.toOrgResponse(ctx, org, userID.(string)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// RequestRoleUpgrade submits a request to upgrade role in an organization
|
// RequestRoleUpgrade submits a request to upgrade role in an organization
|
||||||
// @Summary 申请权限升级
|
// @Summary 申请权限升级
|
||||||
// @Description 现有成员申请更高权限
|
// @Description 现有成员申请更高权限
|
||||||
@@ -1007,6 +1092,7 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
|
|||||||
OwnerID: org.OwnerID,
|
OwnerID: org.OwnerID,
|
||||||
IsOwner: org.OwnerID == currentUserID,
|
IsOwner: org.OwnerID == currentUserID,
|
||||||
RequireApproval: org.RequireApproval,
|
RequireApproval: org.RequireApproval,
|
||||||
|
Searchable: org.Searchable,
|
||||||
InviteCodeValidityDays: org.InviteCodeValidityDays,
|
InviteCodeValidityDays: org.InviteCodeValidityDays,
|
||||||
CreatedAt: org.CreatedAt,
|
CreatedAt: org.CreatedAt,
|
||||||
UpdatedAt: org.UpdatedAt,
|
UpdatedAt: org.UpdatedAt,
|
||||||
|
|||||||
@@ -468,6 +468,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
orgs.POST("/join", orgHandler.JoinByInviteCode)
|
orgs.POST("/join", orgHandler.JoinByInviteCode)
|
||||||
// Submit join request (for organizations that require approval)
|
// Submit join request (for organizations that require approval)
|
||||||
orgs.POST("/join-request", orgHandler.SubmitJoinRequest)
|
orgs.POST("/join-request", orgHandler.SubmitJoinRequest)
|
||||||
|
// Search searchable (discoverable) organizations
|
||||||
|
orgs.GET("/search", orgHandler.SearchOrganizations)
|
||||||
|
// Join searchable organization by ID (no invite code)
|
||||||
|
orgs.POST("/join-by-id", orgHandler.JoinByOrganizationID)
|
||||||
// Get organization by ID
|
// Get organization by ID
|
||||||
orgs.GET("/:id", orgHandler.GetOrganization)
|
orgs.GET("/:id", orgHandler.GetOrganization)
|
||||||
// Update organization
|
// Update organization
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ type OrganizationService interface {
|
|||||||
// Invite Code
|
// Invite Code
|
||||||
GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error)
|
GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error)
|
||||||
JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error)
|
JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error)
|
||||||
|
// Searchable organizations (discovery)
|
||||||
|
SearchSearchableOrganizations(ctx context.Context, userID string, query string, limit int) (*types.ListSearchableOrganizationsResponse, error)
|
||||||
|
JoinByOrganizationID(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.Organization, error)
|
||||||
|
|
||||||
// Join Requests (for organizations that require approval)
|
// Join Requests (for organizations that require approval)
|
||||||
SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error)
|
SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error)
|
||||||
@@ -50,6 +53,7 @@ type OrganizationRepository interface {
|
|||||||
GetByID(ctx context.Context, id string) (*types.Organization, error)
|
GetByID(ctx context.Context, id string) (*types.Organization, error)
|
||||||
GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||||
ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error)
|
ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error)
|
||||||
|
ListSearchable(ctx context.Context, query string, limit int) ([]*types.Organization, error)
|
||||||
Update(ctx context.Context, org *types.Organization) error
|
Update(ctx context.Context, org *types.Organization) error
|
||||||
Delete(ctx context.Context, id string) error
|
Delete(ctx context.Context, id string) error
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ type Organization struct {
|
|||||||
InviteCodeValidityDays int `json:"invite_code_validity_days" gorm:"default:7"`
|
InviteCodeValidityDays int `json:"invite_code_validity_days" gorm:"default:7"`
|
||||||
// Whether joining requires admin approval
|
// Whether joining requires admin approval
|
||||||
RequireApproval bool `json:"require_approval" gorm:"default:false"`
|
RequireApproval bool `json:"require_approval" gorm:"default:false"`
|
||||||
|
// Whether the space is open for search (discoverable; non-members can search and join by org ID)
|
||||||
|
Searchable bool `json:"searchable" gorm:"default:false"`
|
||||||
// Creation time
|
// Creation time
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
// Last updated time
|
// Last updated time
|
||||||
@@ -224,6 +226,7 @@ type UpdateOrganizationRequest struct {
|
|||||||
Description *string `json:"description" binding:"omitempty,max=1000"`
|
Description *string `json:"description" binding:"omitempty,max=1000"`
|
||||||
Avatar *string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
Avatar *string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
||||||
RequireApproval *bool `json:"require_approval"`
|
RequireApproval *bool `json:"require_approval"`
|
||||||
|
Searchable *bool `json:"searchable"` // open for search so others can discover and join
|
||||||
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // 0=never, 1, 7, 30
|
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // 0=never, 1, 7, 30
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,6 +294,7 @@ type OrganizationResponse struct {
|
|||||||
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
|
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
|
||||||
InviteCodeValidityDays int `json:"invite_code_validity_days"`
|
InviteCodeValidityDays int `json:"invite_code_validity_days"`
|
||||||
RequireApproval bool `json:"require_approval"`
|
RequireApproval bool `json:"require_approval"`
|
||||||
|
Searchable bool `json:"searchable"`
|
||||||
MemberCount int `json:"member_count"`
|
MemberCount int `json:"member_count"`
|
||||||
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
|
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
|
||||||
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
|
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
|
||||||
@@ -339,6 +343,31 @@ type ListOrganizationsResponse struct {
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SearchableOrganizationItem is a searchable org item for discovery (no invite code)
|
||||||
|
type SearchableOrganizationItem struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Avatar string `json:"avatar,omitempty"`
|
||||||
|
MemberCount int `json:"member_count"`
|
||||||
|
ShareCount int `json:"share_count"`
|
||||||
|
IsAlreadyMember bool `json:"is_already_member"`
|
||||||
|
RequireApproval bool `json:"require_approval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListSearchableOrganizationsResponse is the response for searching discoverable organizations
|
||||||
|
type ListSearchableOrganizationsResponse struct {
|
||||||
|
Organizations []SearchableOrganizationItem `json:"organizations"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinByOrganizationIDRequest is used to join a searchable organization by ID (no invite code)
|
||||||
|
type JoinByOrganizationIDRequest struct {
|
||||||
|
OrganizationID string `json:"organization_id" binding:"required"`
|
||||||
|
Message string `json:"message" binding:"max=500"` // Optional message for join request
|
||||||
|
Role OrgMemberRole `json:"role"` // Optional: requested role (admin/editor/viewer); default viewer
|
||||||
|
}
|
||||||
|
|
||||||
// JoinRequestResponse represents a join request in API responses
|
// JoinRequestResponse represents a join request in API responses
|
||||||
type JoinRequestResponse struct {
|
type JoinRequestResponse struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Rollback: 000012_organizations_searchable
|
||||||
|
ALTER TABLE organizations DROP COLUMN IF EXISTS searchable;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Migration: 000012_organizations_searchable
|
||||||
|
-- Description: Add searchable flag to organizations (open for discovery)
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000012] Adding searchable to organizations...'; END $$;
|
||||||
|
|
||||||
|
ALTER TABLE organizations ADD COLUMN IF NOT EXISTS searchable BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
COMMENT ON COLUMN organizations.searchable IS 'When true, space appears in search and can be joined by org ID';
|
||||||
|
|
||||||
|
DO $$ BEGIN RAISE NOTICE '[Migration 000012] Organizations searchable column added.'; END $$;
|
||||||
Reference in New Issue
Block a user