feat(api): integrate per-organization resource counts into organization listing
- Added `resource_counts` to the `ListOrganizationsResponse` to include per-organization knowledge base and agent counts, enhancing the sidebar display. - Removed the deprecated `getMeResourceCounts` API endpoint, consolidating resource count retrieval into the organization listing. - Updated the organization store to manage and utilize the new resource counts effectively. - Adjusted UI components to leverage the new resource counts structure, improving data retrieval and display for agents and knowledge bases. This update streamlines resource count management and enhances the user experience by providing relevant data in a single API call.
This commit is contained in:
@@ -159,9 +159,16 @@ export interface ApiResponse<T> {
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** Per-org resource counts (included in list my organizations to avoid extra GET /me/resource-counts) */
|
||||
export interface ResourceCountsByOrg {
|
||||
knowledge_bases: { by_organization: Record<string, number> }
|
||||
agents: { by_organization: Record<string, number> }
|
||||
}
|
||||
|
||||
export interface ListOrganizationsResponse {
|
||||
organizations: Organization[]
|
||||
total: number
|
||||
resource_counts?: ResourceCountsByOrg
|
||||
}
|
||||
|
||||
export interface ListMembersResponse {
|
||||
@@ -642,25 +649,6 @@ export async function listSharedAgents(): Promise<ApiResponse<SharedAgentInfo[]>
|
||||
}
|
||||
}
|
||||
|
||||
/** Response of GET /me/resource-counts: per-org counts for sidebar (one request instead of N). */
|
||||
export interface MeResourceCountsResponse {
|
||||
knowledge_bases: { by_organization: Record<string, number> }
|
||||
agents: { by_organization: Record<string, number> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get per-organization resource counts for list sidebar (one request).
|
||||
* 全部 total is not included; frontend keeps 全部 = 我的 + 他人共享给我.
|
||||
*/
|
||||
export async function getMeResourceCounts(): Promise<ApiResponse<MeResourceCountsResponse>> {
|
||||
try {
|
||||
const response = await get('/api/v1/me/resource-counts')
|
||||
return response as unknown as ApiResponse<MeResourceCountsResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to get resource counts' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all agents in an organization (including those shared by current tenant), for list page when a space is selected.
|
||||
*/
|
||||
|
||||
@@ -5,7 +5,8 @@ import type {
|
||||
OrganizationMember,
|
||||
SharedKnowledgeBase,
|
||||
SharedAgentInfo,
|
||||
OrganizationPreview
|
||||
OrganizationPreview,
|
||||
ResourceCountsByOrg
|
||||
} from '@/api/organization'
|
||||
import {
|
||||
listMyOrganizations,
|
||||
@@ -33,6 +34,10 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
const previewData = ref<OrganizationPreview | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
/** 各空间内知识库/智能体数量(由 GET /organizations 的 resource_counts 填充,供列表侧栏使用) */
|
||||
const resourceCounts = ref<ResourceCountsByOrg | null>(null)
|
||||
/** 用于去重:同一时刻只允许一次 GET /organizations 请求 */
|
||||
let fetchOrganizationsPromise: Promise<void> | null = null
|
||||
|
||||
// Computed
|
||||
const myOrganizations = computed(() => organizations.value)
|
||||
@@ -53,23 +58,32 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
// Actions
|
||||
|
||||
/**
|
||||
* Fetch all organizations the user belongs to
|
||||
* Fetch all organizations the user belongs to.
|
||||
* 去重:并发调用只发一次请求,共用同一 Promise。
|
||||
*/
|
||||
async function fetchOrganizations() {
|
||||
if (fetchOrganizationsPromise) return fetchOrganizationsPromise
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await listMyOrganizations()
|
||||
if (response.success && response.data) {
|
||||
organizations.value = response.data.organizations
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch organizations'
|
||||
fetchOrganizationsPromise = (async () => {
|
||||
try {
|
||||
const response = await listMyOrganizations()
|
||||
if (response.success && response.data) {
|
||||
organizations.value = response.data.organizations
|
||||
resourceCounts.value = response.data.resource_counts ?? null
|
||||
} else {
|
||||
resourceCounts.value = null
|
||||
error.value = response.message || 'Failed to fetch organizations'
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch organizations'
|
||||
resourceCounts.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
fetchOrganizationsPromise = null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch organizations'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})()
|
||||
return fetchOrganizationsPromise
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -413,6 +427,7 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
currentMembers.value = []
|
||||
sharedKnowledgeBases.value = []
|
||||
sharedAgents.value = []
|
||||
resourceCounts.value = null
|
||||
previewData.value = null
|
||||
error.value = null
|
||||
}
|
||||
@@ -424,6 +439,7 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
currentMembers,
|
||||
sharedKnowledgeBases,
|
||||
sharedAgents,
|
||||
resourceCounts,
|
||||
previewData,
|
||||
loading,
|
||||
error,
|
||||
|
||||
@@ -540,7 +540,7 @@ import { formatStringDate } from '@/utils/index'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { createSessions } from '@/api/chat/index'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { setSharedAgentDisabledByMe, listOrganizationSharedAgents, getMeResourceCounts } from '@/api/organization'
|
||||
import { setSharedAgentDisabledByMe, listOrganizationSharedAgents } from '@/api/organization'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { useMenuStore } from '@/stores/menu'
|
||||
import type { SharedAgentInfo, OrganizationSharedAgentItem } from '@/api/organization'
|
||||
@@ -674,12 +674,9 @@ const fetchList = () => {
|
||||
orgStore.fetchSharedAgents(),
|
||||
orgStore.fetchOrganizations()
|
||||
]).finally(() => { loading.value = false }).then(() => {
|
||||
// 一次请求拉取各空间内全部智能体数量(含我共享的),用于侧栏展示
|
||||
getMeResourceCounts().then((res) => {
|
||||
if (res.success && res.data?.agents?.by_organization) {
|
||||
spaceAgentCountByOrg.value = { ...res.data.agents.by_organization }
|
||||
}
|
||||
})
|
||||
// 各空间智能体数量已由 GET /organizations 的 resource_counts 带回,存于 orgStore.resourceCounts
|
||||
const counts = orgStore.resourceCounts?.agents?.by_organization
|
||||
if (counts) spaceAgentCountByOrg.value = { ...counts }
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ import { listKnowledgeBases, deleteKnowledgeBase } from '@/api/knowledge-base'
|
||||
import { formatStringDate } from '@/utils/index'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { listOrganizationSharedKnowledgeBases, getMeResourceCounts, type SharedKnowledgeBase, type OrganizationSharedKnowledgeBaseItem, type SourceFromAgentInfo } from '@/api/organization'
|
||||
import { listOrganizationSharedKnowledgeBases, type SharedKnowledgeBase, type OrganizationSharedKnowledgeBaseItem, type SourceFromAgentInfo } from '@/api/organization'
|
||||
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue'
|
||||
import ShareKnowledgeBaseDialog from '@/components/ShareKnowledgeBaseDialog.vue'
|
||||
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
|
||||
@@ -703,12 +703,9 @@ const fetchList = () => {
|
||||
orgStore.fetchSharedKnowledgeBases(),
|
||||
orgStore.fetchOrganizations()
|
||||
]).finally(() => { loading.value = false }).then(() => {
|
||||
// 一次请求拉取各空间内全部知识库数量(含我共享的),用于侧栏展示
|
||||
getMeResourceCounts().then((res) => {
|
||||
if (res.success && res.data?.knowledge_bases?.by_organization) {
|
||||
spaceCountByOrg.value = { ...res.data.knowledge_bases.by_organization }
|
||||
}
|
||||
})
|
||||
// 各空间知识库数量已由 GET /organizations 的 resource_counts 带回,存于 orgStore.resourceCounts
|
||||
const counts = orgStore.resourceCounts?.knowledge_bases?.by_organization
|
||||
if (counts) spaceCountByOrg.value = { ...counts }
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -118,6 +118,25 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganizations lists all share records for the given organizations (batch).
|
||||
func (r *agentShareRepository) ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var shares []*types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
|
||||
Preload("Agent").
|
||||
Preload("Organization").
|
||||
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
|
||||
Order("agent_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted agents.
|
||||
func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
|
||||
@@ -126,6 +126,25 @@ func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganizations lists all share records for the given organizations (batch).
|
||||
func (r *kbShareRepository) ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListSharedKBsForUser lists all knowledge bases shared to organizations that the user belongs to.
|
||||
// Excludes shares for soft-deleted organizations and soft-deleted knowledge bases.
|
||||
func (r *kbShareRepository) ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
|
||||
@@ -185,6 +185,27 @@ func (r *organizationRepository) GetMember(ctx context.Context, orgID string, us
|
||||
return &member, nil
|
||||
}
|
||||
|
||||
// ListMembersByUserForOrgs returns one member record per org where the user is a member (batch).
|
||||
func (r *organizationRepository) ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string]*types.OrganizationMember), nil
|
||||
}
|
||||
var members []*types.OrganizationMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND organization_id IN ?", userID, orgIDs).
|
||||
Find(&members).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]*types.OrganizationMember, len(members))
|
||||
for _, m := range members {
|
||||
if m != nil {
|
||||
out[m.OrganizationID] = m
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CountMembers counts the number of members in an organization
|
||||
func (r *organizationRepository) CountMembers(ctx context.Context, orgID string) (int64, error) {
|
||||
var count int64
|
||||
|
||||
@@ -294,6 +294,76 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListSharedAgentsInOrganizations returns per-org agent lists (batch); only orgs where user is member.
|
||||
func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error) {
|
||||
out := make(map[string][]*types.OrganizationSharedAgentItem)
|
||||
if len(orgIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shares, err := s.shareRepo.ListByOrganizations(ctx, orgIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byOrg := make(map[string][]*types.AgentShare)
|
||||
for _, share := range shares {
|
||||
if share != nil && members[share.OrganizationID] != nil {
|
||||
byOrg[share.OrganizationID] = append(byOrg[share.OrganizationID], share)
|
||||
}
|
||||
}
|
||||
disabledSet := make(map[string]bool)
|
||||
if disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID); err == nil {
|
||||
for _, d := range disabledList {
|
||||
disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true
|
||||
}
|
||||
}
|
||||
for orgID, list := range byOrg {
|
||||
member := members[orgID]
|
||||
result := make([]*types.OrganizationSharedAgentItem, 0, len(list))
|
||||
for _, share := range list {
|
||||
if share.Agent == nil {
|
||||
continue
|
||||
}
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
orgName := ""
|
||||
if share.Organization != nil {
|
||||
orgName = share.Organization.Name
|
||||
}
|
||||
info := &types.SharedAgentInfo{
|
||||
Agent: share.Agent,
|
||||
ShareID: share.ID,
|
||||
OrganizationID: share.OrganizationID,
|
||||
OrgName: orgName,
|
||||
Permission: effectivePermission,
|
||||
SourceTenantID: share.SourceTenantID,
|
||||
SharedAt: share.CreatedAt,
|
||||
SharedByUserID: share.SharedByUserID,
|
||||
}
|
||||
if share.SharedByUserID != "" {
|
||||
if u, err := s.userRepo.GetUserByID(ctx, share.SharedByUserID); err == nil && u != nil {
|
||||
info.SharedByUsername = u.Username
|
||||
}
|
||||
}
|
||||
item := &types.OrganizationSharedAgentItem{
|
||||
SharedAgentInfo: *info,
|
||||
IsMine: share.SourceTenantID == currentTenantID,
|
||||
}
|
||||
if item.Agent != nil && !item.IsMine {
|
||||
item.DisabledByMe = disabledSet[fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)]
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
out[orgID] = result
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CountByOrganizations returns share counts per organization (for list sidebar); excludes deleted agents
|
||||
func (s *agentShareService) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountByOrganizations(ctx, orgIDs)
|
||||
|
||||
@@ -348,6 +348,35 @@ func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Cont
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch); only orgs where user is member.
|
||||
func (s *kbShareService) ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error) {
|
||||
if len(orgIDs) == 0 {
|
||||
return make(map[string][]string), nil
|
||||
}
|
||||
members, err := s.orgRepo.ListMembersByUserForOrgs(ctx, userID, orgIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shares, err := s.shareRepo.ListByOrganizations(ctx, orgIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byOrg := make(map[string][]string)
|
||||
for _, share := range shares {
|
||||
if share == nil || members[share.OrganizationID] == nil {
|
||||
continue
|
||||
}
|
||||
kbID := share.KnowledgeBaseID
|
||||
if kbID == "" && share.KnowledgeBase != nil {
|
||||
kbID = share.KnowledgeBase.ID
|
||||
}
|
||||
if kbID != "" {
|
||||
byOrg[share.OrganizationID] = append(byOrg[share.OrganizationID], kbID)
|
||||
}
|
||||
}
|
||||
return byOrg, nil
|
||||
}
|
||||
|
||||
// GetShare gets a share by ID
|
||||
func (s *kbShareService) GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error) {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
|
||||
@@ -23,7 +23,7 @@ type OrganizationHandler struct {
|
||||
agentShareService interfaces.AgentShareService
|
||||
customAgentService interfaces.CustomAgentService
|
||||
userService interfaces.UserService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
}
|
||||
@@ -122,9 +122,10 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListMyOrganizations lists organizations that the current user belongs to
|
||||
// ListMyOrganizations lists organizations that the current user belongs to.
|
||||
// Response includes resource_counts (per-org KB/agent counts) for list sidebar so frontend does not need a separate GET /me/resource-counts.
|
||||
// @Summary 获取我的组织列表
|
||||
// @Description 获取当前用户所属的所有组织
|
||||
// @Description 获取当前用户所属的所有组织,并附带各空间内知识库/智能体数量
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.ListOrganizationsResponse
|
||||
@@ -132,8 +133,8 @@ func (h *OrganizationHandler) GetOrganization(c *gin.Context) {
|
||||
// @Router /organizations [get]
|
||||
func (h *OrganizationHandler) ListMyOrganizations(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
userID := c.GetString(types.UserIDContextKey.String())
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
orgs, err := h.orgService.ListUserOrganizations(ctx, userID)
|
||||
if err != nil {
|
||||
@@ -147,15 +148,127 @@ func (h *OrganizationHandler) ListMyOrganizations(c *gin.Context) {
|
||||
response = append(response, h.toOrgResponse(ctx, org, userID))
|
||||
}
|
||||
|
||||
resp := types.ListOrganizationsResponse{
|
||||
Organizations: response,
|
||||
Total: int64(len(response)),
|
||||
}
|
||||
// 附带各空间资源数量,供知识库/智能体列表页侧栏展示
|
||||
resp.ResourceCounts = h.buildResourceCountsByOrg(ctx, orgs, userID, tenantID)
|
||||
if resp.ResourceCounts != nil {
|
||||
// 补齐未出现在 map 中的 org 为 0
|
||||
for _, o := range orgs {
|
||||
if _, ok := resp.ResourceCounts.KnowledgeBases.ByOrganization[o.ID]; !ok {
|
||||
resp.ResourceCounts.KnowledgeBases.ByOrganization[o.ID] = 0
|
||||
}
|
||||
if _, ok := resp.ResourceCounts.Agents.ByOrganization[o.ID]; !ok {
|
||||
resp.ResourceCounts.Agents.ByOrganization[o.ID] = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": types.ListOrganizationsResponse{
|
||||
Organizations: response,
|
||||
Total: int64(len(response)),
|
||||
},
|
||||
"data": resp,
|
||||
})
|
||||
}
|
||||
|
||||
// buildResourceCountsByOrg 返回各空间内知识库数与智能体数,供 ListMyOrganizations 和侧栏使用;失败时返回 nil。
|
||||
// 使用批量接口:一次拉取所有空间的直接共享 KB ID、一次拉取所有空间的智能体列表,再在内存中按空间合并计数。
|
||||
func (h *OrganizationHandler) buildResourceCountsByOrg(ctx context.Context, orgs []*types.Organization, userID string, tenantID uint64) *types.ResourceCountsByOrgResponse {
|
||||
orgIDs := make([]string, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
orgIDs = append(orgIDs, o.ID)
|
||||
}
|
||||
agentCounts, err := h.agentShareService.CountByOrganizations(ctx, orgIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "buildResourceCountsByOrg CountByOrganizations: %v", err)
|
||||
return nil
|
||||
}
|
||||
directKBIDsByOrg, err := h.shareService.ListSharedKnowledgeBaseIDsByOrganizations(ctx, orgIDs, userID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedKnowledgeBaseIDsByOrganizations: %v", err)
|
||||
return nil
|
||||
}
|
||||
agentListByOrg, err := h.agentShareService.ListSharedAgentsInOrganizations(ctx, orgIDs, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "buildResourceCountsByOrg ListSharedAgentsInOrganizations: %v", err)
|
||||
return nil
|
||||
}
|
||||
byOrgKB := make(map[string]int)
|
||||
tenantKBCache := make(map[uint64][]string) // cache ListKnowledgeBasesByTenantID by tenantID
|
||||
for _, o := range orgs {
|
||||
oid := o.ID
|
||||
directIDs := directKBIDsByOrg[oid]
|
||||
directSet := make(map[string]bool)
|
||||
for _, id := range directIDs {
|
||||
directSet[id] = true
|
||||
}
|
||||
count := len(directIDs)
|
||||
for _, item := range agentListByOrg[oid] {
|
||||
if item.Agent == nil {
|
||||
continue
|
||||
}
|
||||
agent := item.Agent
|
||||
mode := agent.Config.KBSelectionMode
|
||||
if mode == "none" {
|
||||
continue
|
||||
}
|
||||
var kbIDs []string
|
||||
switch mode {
|
||||
case "selected":
|
||||
if len(agent.Config.KnowledgeBases) == 0 {
|
||||
continue
|
||||
}
|
||||
kbIDs = agent.Config.KnowledgeBases
|
||||
case "all":
|
||||
tid := agent.TenantID
|
||||
if _, ok := tenantKBCache[tid]; !ok {
|
||||
kbs, err := h.kbService.ListKnowledgeBasesByTenantID(ctx, tid)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "ListKnowledgeBasesByTenantID tenant %d: %v", tid, err)
|
||||
tenantKBCache[tid] = nil
|
||||
continue
|
||||
}
|
||||
ids := make([]string, 0, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb != nil && kb.ID != "" {
|
||||
ids = append(ids, kb.ID)
|
||||
}
|
||||
}
|
||||
tenantKBCache[tid] = ids
|
||||
}
|
||||
kbIDs = tenantKBCache[tid]
|
||||
default:
|
||||
if len(agent.Config.KnowledgeBases) > 0 {
|
||||
kbIDs = agent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
for _, kbID := range kbIDs {
|
||||
if kbID != "" && !directSet[kbID] {
|
||||
directSet[kbID] = true
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
byOrgKB[oid] = count
|
||||
}
|
||||
byOrgAgent := make(map[string]int)
|
||||
for _, o := range orgs {
|
||||
byOrgAgent[o.ID] = 0
|
||||
}
|
||||
for id, n := range agentCounts {
|
||||
byOrgAgent[id] = int(n)
|
||||
}
|
||||
return &types.ResourceCountsByOrgResponse{
|
||||
KnowledgeBases: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgKB},
|
||||
Agents: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgAgent},
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateOrganization updates an organization
|
||||
// @Summary 更新组织
|
||||
// @Description 更新组织信息(需要管理员权限)
|
||||
@@ -1257,73 +1370,6 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"shares": response, "total": len(response)}})
|
||||
}
|
||||
|
||||
// GetMeResourceCounts returns per-organization resource counts for the list sidebar (one request instead of N).
|
||||
// 全部 total is not returned here; frontend keeps 全部 = 我的 + 他人共享给我(与「全部」Tab 一致).
|
||||
// @Summary 获取各空间资源数量(侧栏用)
|
||||
// @Description 一次请求返回各空间内知识库/智能体数量(含我共享的),用于列表页侧栏展示
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Success 200 {object} types.ResourceCountsByOrgResponse
|
||||
// @Security Bearer
|
||||
// @Router /me/resource-counts [get]
|
||||
func (h *OrganizationHandler) GetMeResourceCounts(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
userID := c.GetString(types.UserIDContextKey.String())
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
orgs, err := h.orgService.ListUserOrganizations(ctx, userID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to list user organizations: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to list organizations"))
|
||||
return
|
||||
}
|
||||
orgIDs := make([]string, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
orgIDs = append(orgIDs, o.ID)
|
||||
}
|
||||
|
||||
agentCounts, err := h.agentShareService.CountByOrganizations(ctx, orgIDs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to count agent shares by org: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to get counts"))
|
||||
return
|
||||
}
|
||||
|
||||
byOrgKB := make(map[string]int)
|
||||
for _, o := range orgs {
|
||||
list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, o.ID, userID, tenantID)
|
||||
if err != nil {
|
||||
if !errors.Is(err, service.ErrUserNotInOrg) {
|
||||
logger.Warnf(ctx, "listSpaceKnowledgeBasesInOrganization org %s: %v", o.ID, err)
|
||||
}
|
||||
byOrgKB[o.ID] = 0
|
||||
continue
|
||||
}
|
||||
byOrgKB[o.ID] = len(list)
|
||||
}
|
||||
byOrgAgent := make(map[string]int)
|
||||
for id, n := range agentCounts {
|
||||
byOrgAgent[id] = int(n)
|
||||
}
|
||||
for _, o := range orgs {
|
||||
if _, ok := byOrgAgent[o.ID]; !ok {
|
||||
byOrgAgent[o.ID] = 0
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": types.ResourceCountsByOrgResponse{
|
||||
KnowledgeBases: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgKB},
|
||||
Agents: struct {
|
||||
ByOrganization map[string]int `json:"by_organization"`
|
||||
}{ByOrganization: byOrgAgent},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ListSharedAgents lists agents shared to the current user
|
||||
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
@@ -534,6 +534,4 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
||||
// Shared agents route
|
||||
r.GET("/shared-agents", orgHandler.ListSharedAgents)
|
||||
r.POST("/shared-agents/disabled", orgHandler.SetSharedAgentDisabledByMe)
|
||||
// Per-org resource counts for list sidebar (one request)
|
||||
r.GET("/me/resource-counts", orgHandler.GetMeResourceCounts)
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ type OrganizationRepository interface {
|
||||
UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error
|
||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
||||
ListMembersByUserForOrgs(ctx context.Context, userID string, orgIDs []string) (map[string]*types.OrganizationMember, error)
|
||||
CountMembers(ctx context.Context, orgID string) (int64, error)
|
||||
|
||||
// Invite code
|
||||
@@ -91,6 +92,8 @@ type KBShareService interface {
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
|
||||
ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error)
|
||||
// ListSharedKnowledgeBaseIDsByOrganizations returns per-org direct shared KB IDs (batch, for sidebar count).
|
||||
ListSharedKnowledgeBaseIDsByOrganizations(ctx context.Context, orgIDs []string, userID string) (map[string][]string, error)
|
||||
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
||||
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
|
||||
@@ -123,6 +126,7 @@ type KBShareRepository interface {
|
||||
// List
|
||||
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.KnowledgeBaseShare, error)
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
|
||||
// Query for user's accessible shared knowledge bases
|
||||
@@ -141,6 +145,8 @@ type AgentShareService interface {
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||
ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error)
|
||||
ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error)
|
||||
// ListSharedAgentsInOrganizations returns per-org agent list (batch, for sidebar count merge).
|
||||
ListSharedAgentsInOrganizations(ctx context.Context, orgIDs []string, userID string, currentTenantID uint64) (map[string][]*types.OrganizationSharedAgentItem, error)
|
||||
// SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-user preference).
|
||||
SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error
|
||||
// GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention.
|
||||
@@ -166,6 +172,7 @@ type AgentShareRepository interface {
|
||||
DeleteByOrganizationID(ctx context.Context, orgID string) error
|
||||
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
|
||||
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error)
|
||||
ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error)
|
||||
CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
|
||||
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
|
||||
|
||||
@@ -438,8 +438,9 @@ type AgentShareResponse struct {
|
||||
|
||||
// ListOrganizationsResponse represents the response for listing organizations
|
||||
type ListOrganizationsResponse struct {
|
||||
Organizations []OrganizationResponse `json:"organizations"`
|
||||
Total int64 `json:"total"`
|
||||
Organizations []OrganizationResponse `json:"organizations"`
|
||||
Total int64 `json:"total"`
|
||||
ResourceCounts *ResourceCountsByOrgResponse `json:"resource_counts,omitempty"` // 各空间内知识库/智能体数量,供列表侧栏展示
|
||||
}
|
||||
|
||||
// ResourceCountsByOrgResponse is the response for GET /me/resource-counts (sidebar counts per space)
|
||||
|
||||
Reference in New Issue
Block a user