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:
wizardchen
2026-01-30 19:20:52 +08:00
committed by lyingbug
parent 760bbffafe
commit 2818a4fe8f
13 changed files with 1065 additions and 312 deletions
@@ -77,10 +77,28 @@ func (r *organizationRepository) ListByUserID(ctx context.Context, userID string
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)
func (r *organizationRepository) Update(ctx context.Context, org *types.Organization) error {
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
}
@@ -170,6 +170,9 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
if req.RequireApproval != nil {
org.RequireApproval = *req.RequireApproval
}
if req.Searchable != nil {
org.Searchable = *req.Searchable
}
if req.InviteCodeValidityDays != nil {
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
return nil, ErrInvalidValidityDays
@@ -185,6 +188,85 @@ func (s *organizationService) UpdateOrganization(ctx context.Context, id string,
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
func (s *organizationService) DeleteOrganization(ctx context.Context, id string, userID string) error {
org, err := s.orgRepo.GetByID(ctx, id)
+86
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"net/http"
"strconv"
"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
// @Summary 申请权限升级
// @Description 现有成员申请更高权限
@@ -1007,6 +1092,7 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
OwnerID: org.OwnerID,
IsOwner: org.OwnerID == currentUserID,
RequireApproval: org.RequireApproval,
Searchable: org.Searchable,
InviteCodeValidityDays: org.InviteCodeValidityDays,
CreatedAt: org.CreatedAt,
UpdatedAt: org.UpdatedAt,
+4
View File
@@ -468,6 +468,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
orgs.POST("/join", orgHandler.JoinByInviteCode)
// Submit join request (for organizations that require approval)
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
orgs.GET("/:id", orgHandler.GetOrganization)
// Update organization
@@ -27,6 +27,9 @@ type OrganizationService interface {
// Invite Code
GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, 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)
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)
GetByInviteCode(ctx context.Context, inviteCode 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
Delete(ctx context.Context, id string) error
+29
View File
@@ -58,6 +58,8 @@ type Organization struct {
InviteCodeValidityDays int `json:"invite_code_validity_days" gorm:"default:7"`
// Whether joining requires admin approval
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
CreatedAt time.Time `json:"created_at"`
// Last updated time
@@ -224,6 +226,7 @@ type UpdateOrganizationRequest struct {
Description *string `json:"description" binding:"omitempty,max=1000"`
Avatar *string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
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
}
@@ -291,6 +294,7 @@ type OrganizationResponse struct {
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
InviteCodeValidityDays int `json:"invite_code_validity_days"`
RequireApproval bool `json:"require_approval"`
Searchable bool `json:"searchable"`
MemberCount int `json:"member_count"`
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
@@ -339,6 +343,31 @@ type ListOrganizationsResponse struct {
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
type JoinRequestResponse struct {
ID string `json:"id"`