feat: add organization management features
- Introduced a new API for organization management, including creation, updating, and deletion of organizations. - Implemented organization sharing functionality for knowledge bases, allowing users to share knowledge bases with specific organizations and set permissions. - Added UI components for organization selection and sharing dialogs. - Enhanced existing components to support organization-related features, including shared knowledge base handling and organization role management. This update enhances collaboration capabilities within the application by allowing users to manage and share knowledge bases across different organizations.main
parent
548450c170
commit
4158773849
|
|
@ -0,0 +1,241 @@
|
|||
# 工作空间(共享空间)说明文档
|
||||
|
||||
本文档说明 WeKnora 中的**工作空间**(产品中又称「共享空间」)功能,包括空间创建与加入、成员角色与权限、知识库共享规则,以及用户对知识库的最终访问权限计算方式。
|
||||
|
||||
---
|
||||
|
||||
## 一、工作空间概述
|
||||
|
||||
### 1.1 什么是工作空间
|
||||
|
||||
工作空间(Organization)是跨租户协作的载体。用户可以在同一系统内属于不同租户(账户),通过**加入同一工作空间**,实现:
|
||||
|
||||
- 共享知识库:将本租户的知识库共享到空间,供空间内其他成员使用;
|
||||
- 访问他人共享的知识库:在「知识库列表」中看到并打开通过空间共享给自己的知识库;
|
||||
- 在对话、智能体等场景中选择并使用这些共享知识库。
|
||||
|
||||
数据与权限关系简要如下:
|
||||
|
||||
- **租户**:知识库的归属单位,每个知识库属于一个租户;
|
||||
- **工作空间**:不拥有知识库,只记录「某知识库被共享到某空间」以及「共享时的权限」;
|
||||
- **成员**:用户通过邀请码或管理员邀请加入空间,在空间内拥有一个角色(管理员 / 编辑者 / 只读)。
|
||||
|
||||
### 1.2 核心概念对照
|
||||
|
||||
| 概念 | 说明 |
|
||||
|------|------|
|
||||
| 工作空间 / 共享空间 | 同一产品中的「组织」(Organization),用于跨租户共享知识库 |
|
||||
| 空间创建者 | 创建该空间的用户,自动成为该空间的管理员,且不可被移除或降级 |
|
||||
| 空间成员 | 通过邀请码加入或由管理员邀请加入的用户,拥有管理员、编辑者或只读之一角色 |
|
||||
| 知识库归属 | 知识库始终属于一个租户;共享到空间不改变归属,只建立「空间 ↔ 知识库」的共享关系 |
|
||||
| 共享关系 | 一条记录表示:某知识库以某种权限(只读/可写)被共享到某工作空间 |
|
||||
|
||||
---
|
||||
|
||||
## 二、工作空间的创建、加入与离开
|
||||
|
||||
### 2.1 创建空间
|
||||
|
||||
- 任意已登录用户均可创建空间。
|
||||
- 创建时需填写空间名称;描述、头像、邀请码有效期等为可选项。
|
||||
- 创建者自动成为该空间的**管理员**,且:
|
||||
- 不能将自己移出空间;
|
||||
- 不能将自己的角色改为编辑者或只读。
|
||||
|
||||
### 2.2 加入空间
|
||||
|
||||
加入方式有两种:
|
||||
|
||||
1. **邀请码直接加入**
|
||||
- 若空间未开启「加入需审批」,用户输入有效邀请码即可加入。
|
||||
- 加入后默认角色为**只读**。
|
||||
2. **提交加入申请(需审批)**
|
||||
- 若空间开启了「加入需审批」,用户输入邀请码后提交加入申请。
|
||||
- 空间管理员审批通过时可指定角色(管理员/编辑者/只读);若不指定,则使用申请时填写的角色或默认只读。
|
||||
- 审批拒绝后,用户不是成员,无法访问该空间及其共享知识库。
|
||||
|
||||
### 2.3 邀请码
|
||||
|
||||
- 仅空间**管理员**可生成或刷新邀请码。
|
||||
- 邀请码可设置有效期(例如 1 天、7 天、30 天或永不过期);过期后需重新生成才能使用。
|
||||
- 同一时间一个空间仅有一个有效邀请码;重新生成会使旧邀请码失效。
|
||||
|
||||
### 2.4 离开空间
|
||||
|
||||
- 成员可主动退出空间(无需管理员同意)。
|
||||
- 管理员可移除其他成员(不能移除空间创建者)。
|
||||
- 退出或移除后,该用户不再拥有该空间内的任何角色,也无法再通过该空间访问其共享的知识库。
|
||||
|
||||
### 2.5 删除空间
|
||||
|
||||
- 仅空间**创建者**可删除空间。
|
||||
- 删除空间时会解除该空间下所有知识库的共享关系,成员将无法再通过该空间访问这些知识库。
|
||||
|
||||
---
|
||||
|
||||
## 三、空间内角色与权限
|
||||
|
||||
工作空间内共有三种角色,权限从高到低为:**管理员 > 编辑者 > 只读**。
|
||||
|
||||
### 3.1 角色定义
|
||||
|
||||
| 角色 | 英文标识 | 说明 |
|
||||
|------|----------|------|
|
||||
| 管理员 | admin | 空间设置、成员、邀请码及知识库共享的全面管理 |
|
||||
| 编辑者 | editor | 可编辑空间内共享的知识库内容,可将自己的知识库共享到空间;不可管理空间设置与成员 |
|
||||
| 只读 | viewer | 仅可查看与检索空间内共享的知识库;不可共享知识库到空间,不可管理空间 |
|
||||
|
||||
### 3.2 权限矩阵(空间内能力)
|
||||
|
||||
| 能力 | 管理员 | 编辑者 | 只读 |
|
||||
|------|--------|--------|------|
|
||||
| 查看、检索空间内共享的知识库 | ✓ | ✓ | ✓ |
|
||||
| 编辑空间内共享的知识库内容 | ✓ | ✓ | ✗ |
|
||||
| **将知识库共享到本空间** | ✓ | ✓ | ✗ |
|
||||
| 管理空间内知识库共享(取消共享、修改共享权限等) | ✓(见下) | 仅限自己发起的共享 | ✗ |
|
||||
| 管理空间设置(名称、描述、头像、邀请码有效期、是否需审批等) | ✓ | ✗ | ✗ |
|
||||
| 管理成员(邀请、移除、修改角色) | ✓ | ✗ | ✗ |
|
||||
| 生成/刷新邀请码 | ✓ | ✗ | ✗ |
|
||||
| 审批加入申请、权限升级申请 | ✓ | ✗ | ✗ |
|
||||
| 提交权限升级申请 | — | ✓ | ✓ |
|
||||
| 退出空间 | ✓ | ✓ | ✓ |
|
||||
|
||||
说明:
|
||||
|
||||
- **「将知识库共享到本空间」**:仅**管理员**和**编辑者**可以执行;只读成员不能把自己的知识库共享到该空间。
|
||||
- **管理空间内知识库共享**:
|
||||
- 共享的发起人可取消自己发起的共享、修改该条共享的权限;
|
||||
- 空间**管理员**可取消任意一条指向本空间的共享(例如内容治理、发起人已离开等)。
|
||||
|
||||
---
|
||||
|
||||
## 四、知识库共享规则
|
||||
|
||||
### 4.1 谁可以发起共享
|
||||
|
||||
- 只有**知识库所属租户下的用户**(即「拥有」该知识库的账户下的用户)才能将该知识库共享到某个工作空间。
|
||||
- 同时,该用户必须是目标工作空间的**成员**,且角色为**管理员**或**编辑者**。
|
||||
即:**只读成员不能把任何知识库(包括自己的)共享到该空间。**
|
||||
|
||||
### 4.2 共享时的权限设置
|
||||
|
||||
将知识库共享到空间时,需为「该空间」指定一个**共享权限**:
|
||||
|
||||
- **只读(viewer)**:空间成员在该知识库上最多只读(实际权限还会受成员在空间内的角色限制,见下)。
|
||||
- **可写(editor)**:空间成员在该知识库上可被赋予编辑能力(同样受成员角色限制)。
|
||||
|
||||
同一知识库可以共享到多个工作空间,且每个空间可以设置不同的共享权限(例如空间 A 只读、空间 B 可写)。
|
||||
|
||||
### 4.3 更新与取消共享
|
||||
|
||||
- **修改某条共享的权限**:仅**发起该次共享的用户**可以修改(只读 ↔ 可写)。
|
||||
- **取消某条共享**:
|
||||
- **发起该次共享的用户**可随时取消;
|
||||
- 目标空间的**管理员**也可取消该空间下的任意共享(包括他人发起的)。
|
||||
|
||||
### 4.4 同一知识库共享到多个空间
|
||||
|
||||
- 允许将同一知识库共享到多个工作空间。
|
||||
- 每个空间一条共享记录,各自独立配置权限(只读/可写)。
|
||||
- 例如:知识库 K 共享到空间 A(只读)、空间 B(可写),互不影响。
|
||||
|
||||
---
|
||||
|
||||
## 五、用户对知识库的最终访问权限
|
||||
|
||||
用户对某个知识库的访问可能来自两种途径,最终权限取「最宽」的一种。
|
||||
|
||||
### 5.1 两种访问来源
|
||||
|
||||
1. **本租户拥有**
|
||||
知识库属于用户当前所在租户 → 用户对该知识库拥有**完整权限**(创建者/管理端意义上的「所有者」权限:可编辑、管理设置、删除知识库等),无需也不依赖工作空间。
|
||||
2. **通过工作空间共享获得**
|
||||
知识库不属于当前租户,但被共享到了用户所在的至少一个工作空间 → 用户通过「成员身份 + 共享设置」得到**受限权限**(见下)。
|
||||
|
||||
若同时满足 1 和 2(例如先通过空间访问,后来切换到知识库所属租户),系统按「本租户拥有」处理,即完整权限。
|
||||
|
||||
### 5.2 单条共享下的「有效权限」
|
||||
|
||||
对**某一条**「知识库 ↔ 空间」的共享而言,用户在该空间内对这份知识库的权限为:
|
||||
|
||||
- **有效权限 = min( 该条共享的权限, 用户在该空间内的角色 )**
|
||||
|
||||
即:取「共享给空间的权限」与「用户在空间内的角色」中**更严格**的一档。
|
||||
|
||||
- 共享权限与角色均按:**只读(viewer) < 编辑(editor) < 管理员(admin)** 比较。
|
||||
- 例如:
|
||||
- 共享为「可写」,用户在空间内是「只读」→ 有效权限为**只读**;
|
||||
- 共享为「只读」,用户在空间内是「编辑者」→ 有效权限为**只读**;
|
||||
- 共享为「可写」,用户在空间内是「编辑者」→ 有效权限为**可写**。
|
||||
|
||||
### 5.3 同一用户通过多个空间访问同一知识库(取高)
|
||||
|
||||
若用户加入了多个工作空间,且同一知识库被共享到了其中多个空间(可能权限不同),则:
|
||||
|
||||
- 先按 5.2 对每个空间分别算出一条「有效权限」;
|
||||
- 用户对该知识库的**最终权限** = 这些有效权限中的**最高**一档(不取低、不取交集)。
|
||||
|
||||
示例:
|
||||
|
||||
- 知识库 K 共享到空间 A(只读)、空间 B(可写);
|
||||
- 用户同时是 A、B 的成员,在 A、B 内都是编辑者;
|
||||
- 通过 A 的有效权限 = 只读,通过 B 的有效权限 = 可写;
|
||||
- 最终用户对 K 的权限 = **可写**。
|
||||
|
||||
这样设计可以避免:用户因同时在一个「只读共享」的空间里而被整体降级为只读。
|
||||
|
||||
### 5.4 权限层级与可执行操作
|
||||
|
||||
| 最终权限 | 可执行操作 |
|
||||
|----------|------------|
|
||||
| 本租户拥有 | 完整管理:编辑内容、修改知识库设置、删除知识库、管理共享到哪些空间等 |
|
||||
| 通过共享获得 · 管理员/编辑 | 在共享范围内:编辑知识库内容(文档/FAQ 等)、检索与问答 |
|
||||
| 通过共享获得 · 只读 | 仅查看与检索、在对话/智能体中使用该知识库进行问答,不可修改内容 |
|
||||
|
||||
(具体接口层是否区分「编辑」与「只读」以该最终权限为准。)
|
||||
|
||||
---
|
||||
|
||||
## 六、典型场景小结
|
||||
|
||||
| 场景 | 结果 |
|
||||
|------|------|
|
||||
| 用户是空间内只读成员 | 不能把任何知识库共享到该空间;只能查看/检索该空间内已共享的知识库,且每条共享的有效权限不会超过「只读」 |
|
||||
| 用户是空间内编辑者 | 可把自己的知识库共享到该空间(可设只读或可写);可编辑空间内已共享的知识库内容(在共享权限允许的前提下);不可管理空间设置与成员 |
|
||||
| 用户是空间内管理员 | 除编辑者能力外,还可管理空间设置、成员、邀请码、审批加入/升级,以及取消空间内任意知识库共享 |
|
||||
| 同一知识库共享到多空间且权限不同,用户同属多空间 | 用户对该知识库的最终权限 = 各空间有效权限中的**最高**一档 |
|
||||
| 用户退出或被移出空间 | 立即失去通过该空间访问任何共享知识库的权限 |
|
||||
|
||||
---
|
||||
|
||||
## 七、与产品术语的对应
|
||||
|
||||
- 产品中的「共享空间」= 本文的「工作空间」= 系统中的 Organization。
|
||||
- 产品中的「创建者」= 空间创建者 = 自动拥有管理员角色且不可被降级或移出的成员。
|
||||
- 知识库「共享到空间」= 建立一条 KnowledgeBaseShare 记录,并指定该空间下的共享权限(只读/可写)。
|
||||
- 成员在空间内的「权限说明」中「共享知识库到空间」一项:仅管理员和编辑者具备,只读不具备;与本文第四节、第五节规则一致。
|
||||
|
||||
---
|
||||
|
||||
## 八、附录:权限判定流程(实现参考)
|
||||
|
||||
以下为后端逻辑的简要归纳,便于与实现对照:
|
||||
|
||||
1. **判断是否本租户知识库**
|
||||
若 `knowledge_base.tenant_id == current_user.tenant_id` → 直接视为完整权限,不再查共享。
|
||||
|
||||
2. **收集所有「该知识库 → 某空间」的共享**
|
||||
查出所有 `kb_id = 该知识库` 的共享记录。
|
||||
|
||||
3. **对每条共享**
|
||||
- 若用户不是该空间的成员 → 跳过;
|
||||
- 否则:`effective = min(share.permission, user_role_in_org)`(按 admin > editor > viewer 比较取低)。
|
||||
|
||||
4. **合并多条有效权限**
|
||||
最终权限 = 所有 `effective` 中的最大值(即取高)。
|
||||
|
||||
5. **共享到空间的操作权限**
|
||||
- 发起共享:用户须为空间成员且角色为 admin 或 editor;
|
||||
- 取消/修改共享:发起人可操作自己的共享;空间管理员可取消任意指向本空间的共享。
|
||||
|
||||
以上规则与 `internal/application/service/kbshare.go` 及 `organization.go` 中的实现一致。产品界面(如成员列表中的「权限说明」、共享知识库时的空间筛选)已按相同规则做了展示与限制。
|
||||
|
|
@ -97,8 +97,10 @@ export function downKnowledgeDetails(id: string) {
|
|||
return getDown(`/api/v1/knowledge/${id}/download`);
|
||||
}
|
||||
|
||||
export function batchQueryKnowledge(idsQueryString: string) {
|
||||
return get(`/api/v1/knowledge/batch?${idsQueryString}`);
|
||||
/** @param idsQueryString - query string with ids (e.g. ids=xxx&ids=yyy) */
|
||||
export function batchQueryKnowledge(idsQueryString: string, kbId?: string) {
|
||||
const qs = kbId ? `${idsQueryString}&kb_id=${encodeURIComponent(kbId)}` : idsQueryString;
|
||||
return get(`/api/v1/knowledge/batch?${qs}`);
|
||||
}
|
||||
|
||||
export function getKnowledgeDetailsCon(id: string, page: number) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,491 @@
|
|||
import { get, post, put, del } from '@/utils/request'
|
||||
|
||||
// Organization types
|
||||
export interface Organization {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
avatar?: string
|
||||
owner_id: string
|
||||
invite_code?: string
|
||||
invite_code_expires_at?: string | null
|
||||
invite_code_validity_days?: number
|
||||
require_approval?: boolean
|
||||
member_count?: number
|
||||
share_count?: number
|
||||
pending_join_request_count?: number
|
||||
is_owner?: boolean
|
||||
my_role?: string
|
||||
has_pending_upgrade?: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface OrganizationMember {
|
||||
id: string
|
||||
user_id: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
role: 'admin' | 'editor' | 'viewer'
|
||||
tenant_id: number
|
||||
joined_at: string
|
||||
}
|
||||
|
||||
export interface KnowledgeBaseShare {
|
||||
id: string
|
||||
knowledge_base_id: string
|
||||
knowledge_base_name?: string
|
||||
knowledge_base_type?: string
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
organization_id: string
|
||||
organization_name?: string
|
||||
shared_by_user_id: string
|
||||
shared_by_username?: string
|
||||
source_tenant_id: number
|
||||
/** Share permission: what the space was granted (viewer/editor) */
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
/** Current user's role in this organization (admin/editor/viewer) */
|
||||
my_role_in_org?: 'admin' | 'editor' | 'viewer'
|
||||
/** Effective permission for current user = min(permission, my_role_in_org) */
|
||||
my_permission?: 'admin' | 'editor' | 'viewer'
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface SharedKnowledgeBase {
|
||||
knowledge_base: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
type: string
|
||||
knowledge_count?: number
|
||||
chunk_count?: number
|
||||
}
|
||||
share_id: string
|
||||
organization_id: string
|
||||
org_name: string
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
source_tenant_id: number
|
||||
shared_at: string
|
||||
}
|
||||
|
||||
export interface OrganizationPreview {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
avatar?: string
|
||||
member_count: number
|
||||
share_count: number
|
||||
is_already_member: boolean
|
||||
require_approval: boolean
|
||||
created_at: string
|
||||
}
|
||||
|
||||
// Request types
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string
|
||||
description?: string
|
||||
avatar?: string
|
||||
invite_code_validity_days?: number // 0=never, 1, 7, 30; default 7
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationRequest {
|
||||
name?: string
|
||||
description?: string
|
||||
avatar?: string
|
||||
require_approval?: boolean
|
||||
invite_code_validity_days?: number // 0=never, 1, 7, 30
|
||||
}
|
||||
|
||||
export interface UpdateMemberRoleRequest {
|
||||
role: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
export interface JoinOrganizationRequest {
|
||||
invite_code: string
|
||||
}
|
||||
|
||||
export interface ShareKnowledgeBaseRequest {
|
||||
organization_id: string
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
export interface UpdateSharePermissionRequest {
|
||||
permission: 'admin' | 'editor' | 'viewer'
|
||||
}
|
||||
|
||||
// Response types
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean
|
||||
data?: T
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface ListOrganizationsResponse {
|
||||
organizations: Organization[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface ListMembersResponse {
|
||||
members: OrganizationMember[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface JoinRequestResponse {
|
||||
id: string
|
||||
user_id: string
|
||||
username: string
|
||||
email: string
|
||||
message: string
|
||||
request_type: 'join' | 'upgrade' // 'join' for new member, 'upgrade' for role upgrade
|
||||
prev_role?: string // Previous role (only for upgrade requests)
|
||||
requested_role: string // Role applicant requested: admin, editor, viewer
|
||||
status: string
|
||||
created_at: string
|
||||
reviewed_at?: string
|
||||
}
|
||||
|
||||
export interface ListJoinRequestsResponse {
|
||||
requests: JoinRequestResponse[]
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface SubmitJoinRequestRequest {
|
||||
invite_code: string
|
||||
message?: string
|
||||
role?: 'admin' | 'editor' | 'viewer' // Optional: role applicant requests; default viewer
|
||||
}
|
||||
|
||||
export interface ReviewJoinRequestRequest {
|
||||
approved: boolean
|
||||
message?: string
|
||||
role?: 'admin' | 'editor' | 'viewer' // Optional: role to assign when approving; overrides applicant's requested role
|
||||
}
|
||||
|
||||
export interface RequestRoleUpgradeRequest {
|
||||
requested_role: 'admin' | 'editor' | 'viewer' // The role user wants to upgrade to
|
||||
message?: string // Optional message explaining the reason
|
||||
}
|
||||
|
||||
export interface InviteMemberRequest {
|
||||
user_id: string // User ID to invite
|
||||
role: 'admin' | 'editor' | 'viewer' // Role to assign
|
||||
}
|
||||
|
||||
export interface UserSearchResult {
|
||||
id: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
export interface ListSharesResponse {
|
||||
shares: KnowledgeBaseShare[]
|
||||
total: number
|
||||
}
|
||||
|
||||
// Organization API functions
|
||||
|
||||
/**
|
||||
* Create a new organization
|
||||
*/
|
||||
export async function createOrganization(req: CreateOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations', req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to create organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get organization by ID
|
||||
*/
|
||||
export async function getOrganization(id: string): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${id}`)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to get organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List my organizations
|
||||
*/
|
||||
export async function listMyOrganizations(): Promise<ApiResponse<ListOrganizationsResponse>> {
|
||||
try {
|
||||
const response = await get('/api/v1/organizations')
|
||||
return response as unknown as ApiResponse<ListOrganizationsResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organizations' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update organization
|
||||
*/
|
||||
export async function updateOrganization(id: string, req: UpdateOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${id}`, req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete organization
|
||||
*/
|
||||
export async function deleteOrganization(id: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/organizations/${id}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to delete organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join organization by invite code
|
||||
*/
|
||||
export async function joinOrganization(req: JoinOrganizationRequest): Promise<ApiResponse<Organization>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations/join', req)
|
||||
return response as unknown as ApiResponse<Organization>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to join organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a join request (for organizations that require approval).
|
||||
* Optional role: applicant's requested role (admin/editor/viewer); default viewer.
|
||||
*/
|
||||
export async function submitJoinRequest(req: SubmitJoinRequestRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post('/api/v1/organizations/join-request', req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to submit join request' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview organization by invite code (without joining)
|
||||
*/
|
||||
export async function previewOrganization(inviteCode: string): Promise<ApiResponse<OrganizationPreview>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/preview/${inviteCode}`)
|
||||
return response as unknown as ApiResponse<OrganizationPreview>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to preview organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave organization
|
||||
*/
|
||||
export async function leaveOrganization(id: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${id}/leave`, {})
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to leave organization' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request role upgrade in an organization
|
||||
*/
|
||||
export async function requestRoleUpgrade(
|
||||
orgId: string,
|
||||
request: RequestRoleUpgradeRequest
|
||||
): Promise<ApiResponse<JoinRequestResponse>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${orgId}/request-upgrade`, request)
|
||||
return response as unknown as ApiResponse<JoinRequestResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to submit upgrade request' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate new invite code
|
||||
*/
|
||||
export async function generateInviteCode(id: string): Promise<ApiResponse<{ invite_code: string }>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${id}/invite-code`, {})
|
||||
return response as unknown as ApiResponse<{ invite_code: string }>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to generate invite code' }
|
||||
}
|
||||
}
|
||||
|
||||
// Member management
|
||||
|
||||
/**
|
||||
* List organization members
|
||||
*/
|
||||
export async function listMembers(orgId: string): Promise<ApiResponse<ListMembersResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/members`)
|
||||
return response as unknown as ApiResponse<ListMembersResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list members' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update member role
|
||||
*/
|
||||
export async function updateMemberRole(orgId: string, userId: string, req: UpdateMemberRoleRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${orgId}/members/${userId}`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update member role' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove member
|
||||
*/
|
||||
export async function removeMember(orgId: string, userId: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/organizations/${orgId}/members/${userId}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to remove member' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List join requests (pending) for an organization (admin only)
|
||||
*/
|
||||
export async function listJoinRequests(orgId: string): Promise<ApiResponse<ListJoinRequestsResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/join-requests`)
|
||||
return response as unknown as ApiResponse<ListJoinRequestsResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list join requests' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Review join request (approve or reject) - admin only
|
||||
*/
|
||||
export async function reviewJoinRequest(orgId: string, requestId: string, req: ReviewJoinRequestRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/organizations/${orgId}/join-requests/${requestId}/review`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to review join request' }
|
||||
}
|
||||
}
|
||||
|
||||
// Knowledge base sharing
|
||||
|
||||
/**
|
||||
* Share knowledge base to organization
|
||||
*/
|
||||
export async function shareKnowledgeBase(kbId: string, req: ShareKnowledgeBaseRequest): Promise<ApiResponse<KnowledgeBaseShare>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/knowledge-bases/${kbId}/shares`, req)
|
||||
return response as unknown as ApiResponse<KnowledgeBaseShare>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to share knowledge base' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List shares for a knowledge base
|
||||
*/
|
||||
export async function listKBShares(kbId: string): Promise<ApiResponse<ListSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/knowledge-bases/${kbId}/shares`)
|
||||
return response as unknown as ApiResponse<ListSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list shares' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update share permission
|
||||
*/
|
||||
export async function updateSharePermission(kbId: string, shareId: string, req: UpdateSharePermissionRequest): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await put(`/api/v1/knowledge-bases/${kbId}/shares/${shareId}`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to update share permission' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove share
|
||||
*/
|
||||
export async function removeShare(kbId: string, shareId: string): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await del(`/api/v1/knowledge-bases/${kbId}/shares/${shareId}`)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to remove share' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List shared knowledge bases (shared to me through organizations)
|
||||
*/
|
||||
export async function listSharedKnowledgeBases(): Promise<ApiResponse<SharedKnowledgeBase[]>> {
|
||||
try {
|
||||
const response = await get('/api/v1/shared-knowledge-bases')
|
||||
return response as unknown as ApiResponse<SharedKnowledgeBase[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list shared knowledge bases' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List knowledge bases shared to a specific organization
|
||||
*/
|
||||
export async function listOrgShares(orgId: string): Promise<ApiResponse<ListSharesResponse>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/shares`)
|
||||
return response as unknown as ApiResponse<ListSharesResponse>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to list organization shares' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search users for inviting to organization (excludes existing members)
|
||||
*/
|
||||
export async function searchUsersForInvite(
|
||||
orgId: string,
|
||||
query: string,
|
||||
limit: number = 10
|
||||
): Promise<ApiResponse<UserSearchResult[]>> {
|
||||
try {
|
||||
const response = await get(`/api/v1/organizations/${orgId}/search-users?q=${encodeURIComponent(query)}&limit=${limit}`)
|
||||
return response as unknown as ApiResponse<UserSearchResult[]>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to search users' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invite a user to organization directly (admin only)
|
||||
*/
|
||||
export async function inviteMember(
|
||||
orgId: string,
|
||||
req: InviteMemberRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
try {
|
||||
const response = await post(`/api/v1/organizations/${orgId}/invite`, req)
|
||||
return response as unknown as ApiResponse<void>
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || 'Failed to invite member' }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3 10 A4 4 0 0 1 11 10 A4 4 0 0 1 19 10 A4 4 0 0 1 11 10 A4 4 0 0 1 3 10" stroke="#07C05F" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 285 B |
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3 10 A4 4 0 0 1 11 10 A4 4 0 0 1 19 10 A4 4 0 0 1 11 10 A4 4 0 0 1 3 10" stroke="#000000" stroke-opacity=".9" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 305 B |
|
|
@ -44,16 +44,23 @@
|
|||
<TIcon name="app" size="14px" />
|
||||
</div>
|
||||
<span class="agent-option-name">{{ agent.name }}</span>
|
||||
<svg
|
||||
v-if="currentAgentId === agent.id"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="check-icon"
|
||||
>
|
||||
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
|
||||
</svg>
|
||||
<div class="agent-option-actions">
|
||||
<t-tooltip :content="$t('agent.selector.goToSettings')" placement="top">
|
||||
<div class="settings-btn" @click.stop="goToSettings(agent)">
|
||||
<TIcon name="setting" size="14px" />
|
||||
</div>
|
||||
</t-tooltip>
|
||||
<svg
|
||||
v-if="currentAgentId === agent.id"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="check-icon"
|
||||
>
|
||||
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<template #content>
|
||||
<div class="agent-tooltip-content">
|
||||
|
|
@ -103,16 +110,23 @@
|
|||
>
|
||||
<AgentAvatar :name="agent.name" size="small" />
|
||||
<span class="agent-option-name">{{ agent.name }}</span>
|
||||
<svg
|
||||
v-if="currentAgentId === agent.id"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="check-icon"
|
||||
>
|
||||
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
|
||||
</svg>
|
||||
<div class="agent-option-actions">
|
||||
<t-tooltip :content="$t('agent.selector.goToSettings')" placement="top">
|
||||
<div class="settings-btn" @click.stop="goToSettings(agent)">
|
||||
<TIcon name="setting" size="14px" />
|
||||
</div>
|
||||
</t-tooltip>
|
||||
<svg
|
||||
v-if="currentAgentId === agent.id"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 16 16"
|
||||
fill="currentColor"
|
||||
class="check-icon"
|
||||
>
|
||||
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<template #content>
|
||||
<div class="agent-tooltip-content">
|
||||
|
|
@ -164,11 +178,13 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, nextTick } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Icon as TIcon, Popup as TPopup } from 'tdesign-vue-next';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { Icon as TIcon, Popup as TPopup, Tooltip as TTooltip } from 'tdesign-vue-next';
|
||||
import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
|
||||
import AgentAvatar from '@/components/AgentAvatar.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
|
|
@ -242,6 +258,15 @@ const selectAgent = (agent: CustomAgent) => {
|
|||
emit('select', agent);
|
||||
};
|
||||
|
||||
// 跳转到智能体设置页面
|
||||
const goToSettings = (agent: CustomAgent) => {
|
||||
emit('close');
|
||||
router.push({
|
||||
path: '/platform/agents',
|
||||
query: { edit: agent.id }
|
||||
});
|
||||
};
|
||||
|
||||
// 更新下拉框位置(与模型选择器一致)
|
||||
const updateDropdownPosition = () => {
|
||||
if (!props.anchorEl) return;
|
||||
|
|
@ -481,12 +506,40 @@ onMounted(() => {
|
|||
background: var(--td-bg-color-secondarycontainer, #f5f5f5);
|
||||
}
|
||||
|
||||
.agent-option-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 4px;
|
||||
color: var(--td-text-color-placeholder, #999);
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: all 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-secondarycontainer-hover, #e8e8e8);
|
||||
color: var(--td-brand-color, #07c05f);
|
||||
}
|
||||
}
|
||||
|
||||
.agent-option:hover .settings-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.check-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #10b981;
|
||||
flex-shrink: 0;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
// Tooltip 内容样式
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { useSettingsStore } from '@/stores/settings';
|
|||
import { useUIStore } from '@/stores/ui';
|
||||
import { listKnowledgeBases, searchKnowledge, batchQueryKnowledge } from '@/api/knowledge-base';
|
||||
import { stopSession } from '@/api/chat';
|
||||
import { useOrganizationStore } from '@/stores/organization';
|
||||
import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue';
|
||||
import MentionSelector from './MentionSelector.vue';
|
||||
import AgentSelector from './AgentSelector.vue';
|
||||
|
|
@ -21,6 +22,7 @@ const route = useRoute();
|
|||
const router = useRouter();
|
||||
const settingsStore = useSettingsStore();
|
||||
const uiStore = useUIStore();
|
||||
const orgStore = useOrganizationStore();
|
||||
const { t } = useI18n();
|
||||
|
||||
let query = ref("");
|
||||
|
|
@ -143,7 +145,9 @@ const isModelLockedByAgent = computed(() => {
|
|||
// Mention related state
|
||||
const showMention = ref(false);
|
||||
const mentionQuery = ref("");
|
||||
const mentionItems = ref<Array<{ id: string; name: string; type: 'kb' | 'file'; kbType?: 'document' | 'faq'; count?: number; kbName?: string }>>([]);
|
||||
const mentionItems = ref<Array<{ id: string; name: string; type: 'kb' | 'file'; kbType?: 'document' | 'faq'; count?: number; kbName?: string; orgName?: string; kbId?: string }>>([]);
|
||||
/** 文件 ID -> 知识库 ID(用于批量查询时传 kb_id,支持共享知识库下的文档) */
|
||||
const fileIdToKbId = ref<Record<string, string>>({});
|
||||
const mentionActiveIndex = ref(0);
|
||||
const mentionStyle = ref<Record<string, string>>({});
|
||||
const textareaRef = ref<any>(null); // Ref to t-textarea component
|
||||
|
|
@ -180,8 +184,22 @@ const isWebSearchConfigured = ref(false);
|
|||
const knowledgeBases = ref<Array<{ id: string; name: string; type?: 'document' | 'faq'; knowledge_count?: number; chunk_count?: number }>>([]);
|
||||
const fileList = ref<Array<{ id: string; name: string }>>([]);
|
||||
|
||||
// 选中的知识库:包含自己的 + 别人共享的(用于展示已选列表)
|
||||
const selectedKbs = computed(() => {
|
||||
return knowledgeBases.value.filter(kb => selectedKbIds.value.includes(kb.id));
|
||||
const own = knowledgeBases.value.filter(kb => selectedKbIds.value.includes(kb.id));
|
||||
const sharedList = orgStore.sharedKnowledgeBases || [];
|
||||
const sharedMapped = sharedList
|
||||
.filter((s: any) => s.knowledge_base != null && selectedKbIds.value.includes(s.knowledge_base.id))
|
||||
.map((s: any) => ({
|
||||
id: s.knowledge_base.id,
|
||||
name: s.knowledge_base.name,
|
||||
type: s.knowledge_base.type || 'document',
|
||||
knowledge_count: s.knowledge_base.knowledge_count,
|
||||
chunk_count: s.knowledge_base.chunk_count
|
||||
}));
|
||||
const ownIds = new Set(own.map(kb => kb.id));
|
||||
const sharedOnly = sharedMapped.filter((kb: any) => !ownIds.has(kb.id));
|
||||
return [...own, ...sharedOnly];
|
||||
});
|
||||
|
||||
const selectedFiles = computed(() => {
|
||||
|
|
@ -276,23 +294,30 @@ const inputPlaceholder = computed(() => {
|
|||
}
|
||||
});
|
||||
|
||||
// 加载知识库列表
|
||||
// 加载知识库列表(自己的 + 共享的,用于 @ 提及等)
|
||||
const loadKnowledgeBases = async () => {
|
||||
try {
|
||||
const response: any = await listKnowledgeBases();
|
||||
if (response.data && Array.isArray(response.data)) {
|
||||
const validKbs = response.data.filter((kb: any) =>
|
||||
const validKbs = response.data.filter((kb: any) =>
|
||||
kb.embedding_model_id && kb.embedding_model_id !== '' &&
|
||||
kb.summary_model_id && kb.summary_model_id !== ''
|
||||
);
|
||||
knowledgeBases.value = validKbs;
|
||||
|
||||
// 清理无效的知识库ID(已删除或不存在于有效知识库列表中的)
|
||||
|
||||
// 拉取共享知识库(供 @ 提及与清理选中项时识别)
|
||||
await orgStore.fetchSharedKnowledgeBases().catch(() => {});
|
||||
|
||||
// 清理无效的知识库ID:只移除既不在自己列表也不在共享列表中的 ID(保留共享 KB 的选中状态)
|
||||
const validKbIds = new Set(validKbs.map((kb: any) => kb.id));
|
||||
const sharedKbIds = new Set(
|
||||
(orgStore.sharedKnowledgeBases || []).map((s: any) => s.knowledge_base?.id).filter(Boolean)
|
||||
);
|
||||
const currentSelectedIds = settingsStore.settings.selectedKnowledgeBases || [];
|
||||
const validSelectedIds = currentSelectedIds.filter((id: string) => validKbIds.has(id));
|
||||
|
||||
// 如果有无效的ID,更新store
|
||||
const validSelectedIds = currentSelectedIds.filter(
|
||||
(id: string) => validKbIds.has(id) || sharedKbIds.has(id)
|
||||
);
|
||||
|
||||
if (validSelectedIds.length !== currentSelectedIds.length) {
|
||||
settingsStore.selectKnowledgeBases(validSelectedIds);
|
||||
}
|
||||
|
|
@ -305,18 +330,42 @@ const loadKnowledgeBases = async () => {
|
|||
const loadFiles = async () => {
|
||||
const ids = selectedFileIds.value;
|
||||
if (ids.length === 0) return;
|
||||
|
||||
// Filter out files we already have info for
|
||||
|
||||
const missingIds = ids.filter((id: string) => !fileList.value.find(f => f.id === id));
|
||||
if (missingIds.length === 0) return;
|
||||
|
||||
try {
|
||||
const query = new URLSearchParams();
|
||||
missingIds.forEach((id: string) => query.append('ids', id));
|
||||
const res: any = await batchQueryKnowledge(query.toString());
|
||||
if (res.data) {
|
||||
const newFiles = res.data.map((f: any) => ({ id: f.id, name: f.title || f.file_name }));
|
||||
fileList.value = [...fileList.value, ...newFiles];
|
||||
// 按 kb_id 分组:共享知识库下的文档需带 kb_id 才能正确查询
|
||||
const byKbId = new Map<string, string[]>();
|
||||
const noKbId: string[] = [];
|
||||
missingIds.forEach((id: string) => {
|
||||
const kbId = fileIdToKbId.value[id];
|
||||
if (kbId) {
|
||||
if (!byKbId.has(kbId)) byKbId.set(kbId, []);
|
||||
byKbId.get(kbId)!.push(id);
|
||||
} else {
|
||||
noKbId.push(id);
|
||||
}
|
||||
});
|
||||
|
||||
const allNewFiles: Array<{ id: string; name: string }> = [];
|
||||
const runBatch = async (batchIds: string[], kbId?: string) => {
|
||||
const query = new URLSearchParams();
|
||||
batchIds.forEach((id: string) => query.append('ids', id));
|
||||
const res: any = await batchQueryKnowledge(query.toString(), kbId);
|
||||
if (res.data && Array.isArray(res.data)) {
|
||||
res.data.forEach((f: any) => allNewFiles.push({ id: f.id, name: f.title || f.file_name }));
|
||||
}
|
||||
};
|
||||
|
||||
for (const [kbId, batchIds] of byKbId) {
|
||||
await runBatch(batchIds, kbId);
|
||||
}
|
||||
if (noKbId.length > 0) {
|
||||
await runBatch(noKbId);
|
||||
}
|
||||
if (allNewFiles.length > 0) {
|
||||
fileList.value = [...fileList.value, ...allNewFiles];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to load files", e);
|
||||
|
|
@ -583,36 +632,54 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
|
|||
mentionOffset.value = 0;
|
||||
}
|
||||
|
||||
// 根据智能体的 kb_selection_mode 过滤知识库
|
||||
// 根据智能体的 kb_selection_mode 过滤知识库;合并「自己的」+「共享的」知识库
|
||||
let kbItems: any[] = [];
|
||||
if (!append) {
|
||||
// 获取可选的知识库列表
|
||||
let availableKbs = knowledgeBases.value;
|
||||
|
||||
// 自己的知识库(需有 embedding/summary 模型)
|
||||
let availableKbs = [...knowledgeBases.value];
|
||||
// 共享的知识库(有权限的),映射为与 knowledgeBases 同结构便于合并
|
||||
const sharedList = orgStore.sharedKnowledgeBases || [];
|
||||
const sharedKbsForMention = sharedList
|
||||
.filter((s: any) => s.knowledge_base != null)
|
||||
.map((s: any) => ({
|
||||
id: s.knowledge_base.id,
|
||||
name: s.knowledge_base.name,
|
||||
type: s.knowledge_base.type || 'document',
|
||||
knowledge_count: s.knowledge_base.knowledge_count,
|
||||
chunk_count: s.knowledge_base.chunk_count,
|
||||
org_name: s.org_name || ''
|
||||
}));
|
||||
// 去重:若某 KB 既在自己列表又在共享列表,只保留一份(自己的优先)
|
||||
const ownIds = new Set(availableKbs.map((kb: any) => kb.id));
|
||||
sharedKbsForMention.forEach((kb: any) => {
|
||||
if (!ownIds.has(kb.id)) {
|
||||
availableKbs.push(kb);
|
||||
ownIds.add(kb.id);
|
||||
}
|
||||
});
|
||||
|
||||
// 如果智能体有配置,根据 kb_selection_mode 过滤
|
||||
if (hasAgentConfig.value) {
|
||||
const kbMode = agentKBSelectionMode.value;
|
||||
if (kbMode === 'none') {
|
||||
// 不使用知识库,不显示任何知识库
|
||||
availableKbs = [];
|
||||
} else if (kbMode === 'selected') {
|
||||
// 仅显示智能体配置的知识库
|
||||
const configuredKbIds = agentKnowledgeBases.value;
|
||||
availableKbs = knowledgeBases.value.filter(kb => configuredKbIds.includes(kb.id));
|
||||
availableKbs = availableKbs.filter((kb: any) => configuredKbIds.includes(kb.id));
|
||||
}
|
||||
// kbMode === 'all' 时显示全部知识库
|
||||
}
|
||||
|
||||
|
||||
// 按查询过滤
|
||||
const kbs = availableKbs.filter(kb =>
|
||||
!q || kb.name.toLowerCase().includes(q.toLowerCase())
|
||||
const kbs = availableKbs.filter((kb: any) =>
|
||||
!q || (kb.name && kb.name.toLowerCase().includes(q.toLowerCase()))
|
||||
);
|
||||
kbItems = kbs.map(kb => ({
|
||||
id: kb.id,
|
||||
name: kb.name,
|
||||
type: 'kb' as const,
|
||||
kbItems = kbs.map((kb: any) => ({
|
||||
id: kb.id,
|
||||
name: kb.name,
|
||||
type: 'kb' as const,
|
||||
kbType: kb.type || 'document',
|
||||
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0)
|
||||
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
|
||||
orgName: kb.org_name || undefined
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
@ -637,11 +704,12 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
|
|||
files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id));
|
||||
}
|
||||
|
||||
fileItems = files.map((f: any) => ({
|
||||
id: f.id,
|
||||
name: f.title || f.file_name,
|
||||
fileItems = files.map((f: any) => ({
|
||||
id: f.id,
|
||||
name: f.title || f.file_name,
|
||||
type: 'file' as const,
|
||||
kbName: f.knowledge_base_name || ''
|
||||
kbName: f.knowledge_base_name || '',
|
||||
kbId: f.knowledge_base_id || undefined
|
||||
}));
|
||||
}
|
||||
mentionHasMore.value = res.has_more || false;
|
||||
|
|
@ -868,9 +936,12 @@ const onMentionSelect = (item: any) => {
|
|||
settingsStore.addKnowledgeBase(item.id);
|
||||
} else if (item.type === 'file') {
|
||||
settingsStore.addFile(item.id);
|
||||
if (item.kbId) {
|
||||
fileIdToKbId.value[item.id] = item.kbId;
|
||||
}
|
||||
// Add to local cache immediately
|
||||
if (!fileList.value.find(f => f.id === item.id)) {
|
||||
fileList.value.push(item);
|
||||
fileList.value.push({ id: item.id, name: item.name });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -911,6 +982,7 @@ const onMentionSelect = (item: any) => {
|
|||
|
||||
const removeFile = (id: string) => {
|
||||
settingsStore.removeFile(id);
|
||||
delete fileIdToKbId.value[id];
|
||||
};
|
||||
|
||||
const toggleModelSelector = () => {
|
||||
|
|
|
|||
|
|
@ -14,8 +14,11 @@
|
|||
<div class="icon" :class="item.kbType === 'faq' ? 'faq-icon' : 'kb-icon'">
|
||||
<t-icon :name="item.kbType === 'faq' ? 'chat-bubble-help' : 'folder'" />
|
||||
</div>
|
||||
<span class="name">{{ item.name }}</span>
|
||||
<span class="count">({{ item.count || 0 }})</span>
|
||||
<div class="item-main">
|
||||
<span class="name">{{ item.name }}</span>
|
||||
<span class="count">({{ item.count || 0 }})</span>
|
||||
</div>
|
||||
<span v-if="item.orgName" class="org-name">{{ item.orgName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -54,7 +57,7 @@ import { computed, watch, ref, nextTick } from 'vue';
|
|||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
style: any;
|
||||
items: Array<{ id: string; name: string; type: 'kb' | 'file'; kbType?: 'document' | 'faq'; count?: number; kbName?: string }>;
|
||||
items: Array<{ id: string; name: string; type: 'kb' | 'file'; kbType?: 'document' | 'faq'; count?: number; kbName?: string; orgName?: string }>;
|
||||
activeIndex: number;
|
||||
hasMore?: boolean;
|
||||
loading?: boolean;
|
||||
|
|
@ -205,19 +208,42 @@ const scrollToItem = (index: number) => {
|
|||
color: inherit;
|
||||
}
|
||||
|
||||
.name {
|
||||
.item-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 文件项中的 name 需要占据剩余空间,将 kb-name 推到右边 */
|
||||
.mention-item > .name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.count {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--td-font-size-mark-small, 12px);
|
||||
color: var(--td-text-color-secondary, #999);
|
||||
}
|
||||
|
||||
.org-name {
|
||||
flex-shrink: 0;
|
||||
max-width: 72px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--td-font-size-mark-small, 12px);
|
||||
color: var(--td-text-color-placeholder, #999);
|
||||
}
|
||||
|
||||
.kb-name {
|
||||
flex-shrink: 0;
|
||||
max-width: 80px;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,394 @@
|
|||
<template>
|
||||
<t-dialog
|
||||
v-model:visible="dialogVisible"
|
||||
:header="$t('organization.share.title')"
|
||||
width="520px"
|
||||
:footer="false"
|
||||
@close="handleClose"
|
||||
>
|
||||
<!-- Share form -->
|
||||
<div class="share-form" v-if="!showShareList">
|
||||
<t-form :data="shareForm" ref="shareFormRef">
|
||||
<t-form-item
|
||||
:label="$t('organization.share.selectOrg')"
|
||||
name="organization_id"
|
||||
:rules="[{ required: true, message: $t('organization.share.selectOrgPlaceholder') }]"
|
||||
>
|
||||
<t-select
|
||||
v-model="shareForm.organization_id"
|
||||
:placeholder="$t('organization.share.selectOrgPlaceholder')"
|
||||
:loading="loadingOrgs"
|
||||
>
|
||||
<t-option
|
||||
v-for="org in availableOrganizations"
|
||||
:key="org.id"
|
||||
:value="org.id"
|
||||
:label="org.name"
|
||||
>
|
||||
<div class="org-option-content">
|
||||
<div class="org-option-header">
|
||||
<span class="org-option-name">{{ org.name }}</span>
|
||||
<t-tag v-if="org.is_owner" theme="primary" size="small" variant="light">
|
||||
{{ $t('organization.owner') }}
|
||||
</t-tag>
|
||||
<t-tag v-else-if="org.my_role" :theme="org.my_role === 'admin' ? 'warning' : 'default'" size="small" variant="light">
|
||||
{{ $t(`organization.role.${org.my_role}`) }}
|
||||
</t-tag>
|
||||
</div>
|
||||
<div v-if="org.description" class="org-option-desc">{{ org.description }}</div>
|
||||
<div class="org-option-meta">
|
||||
<span class="org-meta-item">
|
||||
<t-icon name="usergroup" size="14px" />
|
||||
{{ org.member_count || 0 }} {{ $t('organization.members') }}
|
||||
</span>
|
||||
<span v-if="org.share_count !== undefined" class="org-meta-item">
|
||||
<t-icon name="share" size="14px" />
|
||||
{{ org.share_count }} {{ $t('organization.share.sharedKBs') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</t-option>
|
||||
</t-select>
|
||||
</t-form-item>
|
||||
<t-form-item :label="$t('organization.share.permission')" name="permission">
|
||||
<t-radio-group v-model="shareForm.permission">
|
||||
<t-radio value="viewer">{{ $t('organization.share.permissionReadonly') }}</t-radio>
|
||||
<t-radio value="editor">{{ $t('organization.share.permissionEditable') }}</t-radio>
|
||||
</t-radio-group>
|
||||
</t-form-item>
|
||||
<div class="permission-tip">
|
||||
<t-icon name="info-circle" size="14px" />
|
||||
<span>{{ $t('organization.share.permissionTip') }}</span>
|
||||
</div>
|
||||
</t-form>
|
||||
<div class="share-actions">
|
||||
<t-button theme="default" @click="showShareList = true" v-if="shares.length > 0">
|
||||
{{ $t('organization.share.sharedTo') }} ({{ shares.length }})
|
||||
</t-button>
|
||||
<div class="spacer"></div>
|
||||
<t-button theme="default" @click="handleClose">{{ $t('common.cancel') }}</t-button>
|
||||
<t-button theme="primary" :loading="submitting" @click="handleShare">
|
||||
{{ $t('common.confirm') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Share list -->
|
||||
<div class="share-list" v-else>
|
||||
<div class="share-list-header">
|
||||
<t-button variant="text" @click="showShareList = false">
|
||||
<template #icon><t-icon name="chevron-left" /></template>
|
||||
{{ $t('common.back') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<div v-if="loadingShares" class="share-list-loading">
|
||||
<t-loading />
|
||||
</div>
|
||||
<div v-else-if="shares.length === 0" class="share-list-empty">
|
||||
{{ $t('organization.share.noShares') }}
|
||||
</div>
|
||||
<div v-else class="share-items">
|
||||
<div v-for="share in shares" :key="share.id" class="share-item">
|
||||
<div class="share-info">
|
||||
<span class="share-org-name">{{ share.organization_name }}</span>
|
||||
<t-tag :theme="share.permission === 'editor' ? 'warning' : 'default'" size="small">
|
||||
{{ share.permission === 'editor' ? $t('organization.share.permissionEditable') : $t('organization.share.permissionReadonly') }}
|
||||
</t-tag>
|
||||
</div>
|
||||
<t-button
|
||||
variant="text"
|
||||
theme="danger"
|
||||
size="small"
|
||||
@click="handleUnshare(share)"
|
||||
>
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { shareKnowledgeBase, listKBShares, removeShare } from '@/api/organization'
|
||||
import type { KnowledgeBaseShare } from '@/api/organization'
|
||||
|
||||
const { t } = useI18n()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
knowledgeBaseId: string
|
||||
knowledgeBaseName?: string
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', value: boolean): void
|
||||
(e: 'shared'): void
|
||||
}>()
|
||||
|
||||
const dialogVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: (val) => emit('update:visible', val)
|
||||
})
|
||||
|
||||
const shareFormRef = ref()
|
||||
const loadingOrgs = ref(false)
|
||||
const loadingShares = ref(false)
|
||||
const submitting = ref(false)
|
||||
const showShareList = ref(false)
|
||||
const shares = ref<(KnowledgeBaseShare & { organization_name?: string })[]>([])
|
||||
|
||||
const shareForm = ref({
|
||||
organization_id: '',
|
||||
permission: 'viewer' as 'admin' | 'editor' | 'viewer'
|
||||
})
|
||||
|
||||
// Only show organizations where user can share (editor or admin); exclude viewer-only orgs and already shared
|
||||
const availableOrganizations = computed(() => {
|
||||
const sharedOrgIds = new Set(shares.value.map(s => s.organization_id))
|
||||
return orgStore.organizations.filter(
|
||||
(org) =>
|
||||
!sharedOrgIds.has(org.id) &&
|
||||
(org.is_owner === true || org.my_role === 'admin' || org.my_role === 'editor')
|
||||
)
|
||||
})
|
||||
|
||||
watch(() => props.visible, async (newVal) => {
|
||||
if (newVal) {
|
||||
showShareList.value = false
|
||||
shareForm.value = { organization_id: '', permission: 'viewer' }
|
||||
await Promise.all([
|
||||
loadOrganizations(),
|
||||
loadShares()
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
async function loadOrganizations() {
|
||||
loadingOrgs.value = true
|
||||
try {
|
||||
await orgStore.fetchOrganizations()
|
||||
} finally {
|
||||
loadingOrgs.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadShares() {
|
||||
if (!props.knowledgeBaseId) return
|
||||
loadingShares.value = true
|
||||
try {
|
||||
const result = await listKBShares(props.knowledgeBaseId)
|
||||
if (result.success && result.data) {
|
||||
// Enrich shares with organization names
|
||||
shares.value = result.data.shares.map((share: KnowledgeBaseShare) => ({
|
||||
...share,
|
||||
organization_name: orgStore.organizations.find(o => o.id === share.organization_id)?.name || share.organization_id
|
||||
}))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load shares:', e)
|
||||
} finally {
|
||||
loadingShares.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleShare() {
|
||||
const valid = await shareFormRef.value?.validate()
|
||||
if (valid !== true) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await shareKnowledgeBase(
|
||||
props.knowledgeBaseId,
|
||||
{ organization_id: shareForm.value.organization_id, permission: shareForm.value.permission }
|
||||
)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.shareSuccess'))
|
||||
await loadShares()
|
||||
shareForm.value = { organization_id: '', permission: 'viewer' }
|
||||
emit('shared')
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.shareFailed'))
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('organization.share.shareFailed'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnshare(share: KnowledgeBaseShare) {
|
||||
try {
|
||||
const result = await removeShare(props.knowledgeBaseId, share.id)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.unshareSuccess'))
|
||||
await loadShares()
|
||||
emit('shared')
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.unshareFailed'))
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('organization.share.unshareFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.share-form {
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.permission-tip {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-radius: 6px;
|
||||
margin-top: 8px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
|
||||
.t-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.share-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 24px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.share-list-header {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.share-list-loading,
|
||||
.share-list-empty {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 32px;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.share-items {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.share-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: var(--td-bg-color-container-hover);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.share-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.share-org-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
// Custom option styles for organization select
|
||||
:deep(.t-select-option) {
|
||||
height: auto;
|
||||
align-items: flex-start;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
:deep(.t-select-option__content) {
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.org-option-content {
|
||||
padding: 2px 0;
|
||||
min-width: 280px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.org-option-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
|
||||
.org-option-name {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
}
|
||||
|
||||
.org-option-desc {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
line-height: 18px;
|
||||
margin-bottom: 6px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.org-option-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
|
||||
.org-meta-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
// Global styles for select dropdown (outside scoped)
|
||||
.t-select__dropdown .t-select-option {
|
||||
height: auto;
|
||||
align-items: flex-start;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.t-select__dropdown .t-select-option__content {
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
<template>
|
||||
<div
|
||||
class="space-avatar"
|
||||
:style="avatarStyle"
|
||||
:class="{ 'space-avatar-small': size === 'small', 'space-avatar-large': size === 'large' }"
|
||||
>
|
||||
<!-- 无限符号:右下角周边点缀,不干扰中央文字 -->
|
||||
<svg class="space-avatar-decoration" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3 10 A4 4 0 0 1 11 10 A4 4 0 0 1 19 10 A4 4 0 0 1 11 10 A4 4 0 0 1 3 10" stroke="rgba(255,255,255,0.25)" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
</svg>
|
||||
<span class="space-avatar-letter" :style="letterStyle">{{ letter }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
name: string;
|
||||
size?: 'small' | 'medium' | 'large';
|
||||
}>(), {
|
||||
size: 'medium'
|
||||
});
|
||||
|
||||
// 预定义渐变色(与项目绿色主色协调,偏空间/协作感)
|
||||
const gradients = [
|
||||
{ from: '#07c05f', to: '#059669' }, // 主绿
|
||||
{ from: '#11998e', to: '#38ef7d' }, // 深绿渐变
|
||||
{ from: '#43e97b', to: '#38f9d7' }, // 绿青
|
||||
{ from: '#02aab0', to: '#00cdac' }, // 青绿
|
||||
{ from: '#36d1dc', to: '#5b86e5' }, // 青蓝
|
||||
{ from: '#4facfe', to: '#00f2fe' }, // 蓝青
|
||||
{ from: '#667eea', to: '#764ba2' }, // 紫蓝
|
||||
{ from: '#4776e6', to: '#8e54e9' }, // 蓝紫
|
||||
{ from: '#56ab2f', to: '#a8e063' }, // 草绿
|
||||
{ from: '#00b09b', to: '#96c93d' }, // 青绿
|
||||
{ from: '#5ee7df', to: '#b490ca' }, // 青紫
|
||||
{ from: '#614385', to: '#516395' }, // 深紫蓝
|
||||
];
|
||||
|
||||
const hashCode = (str: string): number => {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
return Math.abs(hash);
|
||||
};
|
||||
|
||||
const letter = computed(() => {
|
||||
const name = props.name?.trim() || '';
|
||||
if (!name) return '?';
|
||||
const firstChar = name.charAt(0);
|
||||
if (/[a-zA-Z]/.test(firstChar)) return firstChar.toUpperCase();
|
||||
return firstChar;
|
||||
});
|
||||
|
||||
const gradient = computed(() => {
|
||||
const hash = hashCode(props.name || '');
|
||||
return gradients[hash % gradients.length];
|
||||
});
|
||||
|
||||
const avatarStyle = computed(() => {
|
||||
const g = gradient.value;
|
||||
return {
|
||||
background: `linear-gradient(135deg, ${g.from} 0%, ${g.to} 100%)`
|
||||
};
|
||||
});
|
||||
|
||||
const letterStyle = computed(() => {
|
||||
const g = gradient.value;
|
||||
return {
|
||||
textShadow: `0 1px 2px ${g.to}80, 0 0 8px ${g.from}30`
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.space-avatar {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
|
||||
&.space-avatar-small {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 5px;
|
||||
box-shadow: none;
|
||||
|
||||
.space-avatar-letter {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.space-avatar-decoration {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
&.space-avatar-large {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
|
||||
.space-avatar-letter {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.space-avatar-decoration {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
bottom: 2px;
|
||||
width: 40%;
|
||||
height: 40%;
|
||||
opacity: 0.85;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.space-avatar-letter {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -2,6 +2,7 @@ export default {
|
|||
menu: {
|
||||
knowledgeBase: 'Knowledge Base',
|
||||
agents: 'Agents',
|
||||
organizations: 'Shared Spaces',
|
||||
chat: 'Chat',
|
||||
createChat: 'Create Chat',
|
||||
tenant: 'Account Info',
|
||||
|
|
@ -18,6 +19,17 @@ export default {
|
|||
list: 'Knowledge Base List',
|
||||
fileContent: 'File Content',
|
||||
detail: 'Knowledge Base Details',
|
||||
accessInfo: {
|
||||
myRole: 'My role',
|
||||
roleOwner: 'Owner',
|
||||
permissionOwner: 'Edit, manage settings, delete knowledge base',
|
||||
permissionAdmin: 'Edit, manage sharing',
|
||||
permissionEditor: 'Edit documents and categories',
|
||||
permissionViewer: 'View and search only',
|
||||
fromOrg: 'From space',
|
||||
sharedAt: 'Shared at',
|
||||
lastUpdated: 'Last updated',
|
||||
},
|
||||
create: 'Create Knowledge Base',
|
||||
edit: 'Edit Knowledge Base',
|
||||
delete: 'Delete Knowledge Base',
|
||||
|
|
@ -71,6 +83,7 @@ export default {
|
|||
uploadFile: 'Upload File',
|
||||
uploadFileDesc: 'Supports PDF, Word, TXT, etc.',
|
||||
importURL: 'Import from URL',
|
||||
addDocument: 'Add Document',
|
||||
importURLDesc: 'Import via URL link',
|
||||
importURLTitle: 'Import from URL',
|
||||
manualCreate: 'Manual Create',
|
||||
|
|
@ -386,6 +399,7 @@ export default {
|
|||
customSection: 'My Agents',
|
||||
addNew: 'Add New Agent',
|
||||
current: 'Current',
|
||||
goToSettings: 'Settings',
|
||||
},
|
||||
// Built-in agent information
|
||||
builtinInfo: {
|
||||
|
|
@ -808,12 +822,14 @@ export default {
|
|||
}
|
||||
},
|
||||
common: {
|
||||
me: 'Me',
|
||||
confirm: 'Confirm',
|
||||
cancel: 'Cancel',
|
||||
save: 'Save',
|
||||
delete: 'Delete',
|
||||
edit: 'Edit',
|
||||
copy: 'Copy',
|
||||
copied: 'Copied',
|
||||
default: 'Default',
|
||||
create: 'Create',
|
||||
search: 'Search',
|
||||
|
|
@ -1038,16 +1054,35 @@ export default {
|
|||
create: 'Create Knowledge Base',
|
||||
createFAQ: 'Create FAQ Knowledge Base',
|
||||
subtitle: 'Manage and organize your knowledge bases, supporting document-based and FAQ-based knowledge bases',
|
||||
myKnowledgeBases: 'My Knowledge Bases',
|
||||
sharedKnowledgeBases: 'Shared Knowledge Bases',
|
||||
sharedToOrgs: 'Shared to {count} space(s)',
|
||||
sharedLabel: 'Shared',
|
||||
tabs: {
|
||||
all: 'All',
|
||||
myKnowledgeBases: 'My Knowledge Bases',
|
||||
sharedToMe: 'Shared with me',
|
||||
},
|
||||
uninitializedBanner: 'Some knowledge bases are not initialized. Configure model information in settings before adding documents.',
|
||||
empty: {
|
||||
title: 'No knowledge bases yet',
|
||||
description: 'Click "Create Knowledge Base" in the top-right corner to add your first one.'
|
||||
description: 'Click "Create Knowledge Base" in the top-right corner to add your first one.',
|
||||
sharedTitle: 'No shared knowledge bases',
|
||||
sharedDescription: 'You can join a shared space or request others to share knowledge bases with you'
|
||||
},
|
||||
delete: {
|
||||
confirmTitle: 'Delete Confirmation',
|
||||
confirmMessage: 'Are you sure you want to delete the knowledge base "{name}"? This action cannot be undone.',
|
||||
confirmButton: 'Delete'
|
||||
},
|
||||
menu: {
|
||||
viewDetails: 'View Details',
|
||||
},
|
||||
detail: {
|
||||
sourceOrg: 'Source Space',
|
||||
role: 'My Permission',
|
||||
sharedAt: 'Shared At',
|
||||
},
|
||||
messages: {
|
||||
deleted: 'Knowledge base deleted',
|
||||
deleteFailed: 'Failed to delete knowledge base'
|
||||
|
|
@ -1057,6 +1092,27 @@ export default {
|
|||
multimodal: 'Multimodal Enabled',
|
||||
questionGeneration: 'Question Generation Enabled'
|
||||
},
|
||||
detail: {
|
||||
title: 'Shared Knowledge Base',
|
||||
overview: 'Overview',
|
||||
overviewDesc: 'View knowledge base information and source',
|
||||
permission: 'Permission',
|
||||
permissionDesc: 'View your permissions for this knowledge base',
|
||||
sourceOrg: 'Source Space',
|
||||
sharedAt: 'Shared At',
|
||||
myPermission: 'My Permission',
|
||||
canEdit: 'Can edit knowledge base content',
|
||||
canView: 'Can view knowledge base content',
|
||||
canSearch: 'Can search and use knowledge base',
|
||||
goToKb: 'Go to Knowledge Base',
|
||||
enabled: 'Enabled',
|
||||
disabled: 'Disabled',
|
||||
},
|
||||
features: {
|
||||
knowledgeGraph: 'Knowledge Graph',
|
||||
multimodal: 'Multimodal',
|
||||
questionGeneration: 'Question Generation',
|
||||
},
|
||||
processing: 'Processing import task',
|
||||
processingDocuments: 'Processing {count} documents',
|
||||
stats: {
|
||||
|
|
@ -1084,7 +1140,8 @@ export default {
|
|||
chunking: 'Chunking Settings',
|
||||
advanced: 'Advanced Settings',
|
||||
faq: 'FAQ Settings',
|
||||
graph: 'Knowledge Graph'
|
||||
graph: 'Knowledge Graph',
|
||||
share: 'Sharing'
|
||||
},
|
||||
basic: {
|
||||
title: 'Basic Information',
|
||||
|
|
@ -1102,6 +1159,13 @@ export default {
|
|||
create: 'Create Knowledge Base',
|
||||
save: 'Save Configuration'
|
||||
},
|
||||
share: {
|
||||
description: 'Share the knowledge base with spaces so members can access and use it',
|
||||
addShare: 'Share',
|
||||
unshareConfirm: 'Are you sure you want to unshare from "{name}"?',
|
||||
tip1: 'After sharing, space members will access this knowledge base based on the assigned permissions',
|
||||
tip2: 'Editable permission allows members to modify content; Read-only permission only allows retrieval and Q&A'
|
||||
},
|
||||
messages: {
|
||||
loadModelsFailed: 'Failed to load model list',
|
||||
loadDataFailed: 'Failed to load knowledge base data',
|
||||
|
|
@ -1158,6 +1222,8 @@ export default {
|
|||
emptyDesc: 'Click "Create FAQ Entry" above to get started',
|
||||
searchPlaceholder: 'Search standard questions...',
|
||||
searchTest: 'Search Test',
|
||||
addFaq: 'Add FAQ',
|
||||
manageFaq: 'FAQ Actions',
|
||||
searchTestTitle: 'FAQ Search Test',
|
||||
queryLabel: 'Query',
|
||||
queryPlaceholder: 'Enter a question to search',
|
||||
|
|
@ -2278,4 +2344,239 @@ export default {
|
|||
},
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
title: 'Shared Spaces',
|
||||
subtitle: 'Create or join shared spaces to share knowledge bases with your team',
|
||||
createOrg: 'Create Space',
|
||||
joinOrg: 'Join Space',
|
||||
name: 'Space Name',
|
||||
namePlaceholder: 'Enter space name',
|
||||
nameRequired: 'Please enter space name',
|
||||
avatar: 'Space Avatar',
|
||||
description: 'Description',
|
||||
descriptionPlaceholder: 'Enter space description (optional)',
|
||||
noDescription: 'No description',
|
||||
members: 'members',
|
||||
memberCount: 'Member count',
|
||||
owner: 'Creator',
|
||||
inviteCode: 'Invite Code',
|
||||
inviteCodePlaceholder: 'Enter invite code',
|
||||
inviteCodeRequired: 'Please enter invite code',
|
||||
inviteCodeTip: 'Share this invite code with others to let them join your space',
|
||||
refreshInviteCode: 'Refresh Invite Code',
|
||||
inviteCodeRefreshed: 'Invite code refreshed',
|
||||
inviteCodeRefreshFailed: 'Failed to refresh invite code',
|
||||
join: {
|
||||
title: 'Join Space',
|
||||
joining: 'Joining space...',
|
||||
success: 'Successfully joined space!',
|
||||
failed: 'Failed to join space',
|
||||
noCode: 'Invite code not found',
|
||||
goToOrganizations: 'Go to Spaces',
|
||||
confirmTitle: 'Confirm Join Space',
|
||||
confirm: 'Confirm Join',
|
||||
preview: 'Preview & Join',
|
||||
memberCount: '{count} members',
|
||||
shareCount: '{count} shared knowledge bases',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
invalidCode: 'Invalid invite code',
|
||||
},
|
||||
invite: {
|
||||
loading: 'Loading...',
|
||||
previewTitle: 'Join Space',
|
||||
previewInfo: 'Space Overview',
|
||||
inputDesc: 'Enter the invite code (or paste from an invite link) to view the space and join',
|
||||
previewAction: 'View',
|
||||
primaryJoin: 'Join',
|
||||
invalidTitle: 'Invalid Invitation',
|
||||
invalidCode: 'Invite code is invalid or expired',
|
||||
previewFailed: 'Preview failed, please try again',
|
||||
members: 'Members',
|
||||
knowledgeBases: 'Knowledge Bases',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
confirmJoin: 'Confirm Join',
|
||||
submitRequest: 'Request to Join',
|
||||
requireApprovalTip: 'This space requires admin approval to join',
|
||||
approvalLabel: 'Join method',
|
||||
needApproval: 'Requires approval',
|
||||
noApproval: 'No approval required',
|
||||
defaultRoleAfterJoin: 'Default role after joining: {role}',
|
||||
requestRole: 'Requested role',
|
||||
selectRole: 'Select role',
|
||||
messagePlaceholder: 'Optional: message (e.g. intro or reason to join)',
|
||||
joinSuccess: 'Successfully joined space!',
|
||||
joinFailed: 'Failed to join, please try again',
|
||||
requestSubmitted: 'Request submitted, please wait for admin approval',
|
||||
requestFailed: 'Failed to submit request, please try again',
|
||||
viewOrganization: 'View Space',
|
||||
},
|
||||
leave: 'Leave Space',
|
||||
leaveConfirm: 'Are you sure you want to leave this space?',
|
||||
leaveConfirmTitle: 'Leave Space',
|
||||
leaveConfirmMessage: 'Are you sure you want to leave "{name}"? You will lose access to shared knowledge bases.',
|
||||
leaveSuccess: 'Left space successfully',
|
||||
leaveFailed: 'Failed to leave space',
|
||||
deleteConfirm: 'Are you sure you want to delete this space? This action cannot be undone.',
|
||||
deleteConfirmTitle: 'Delete Space',
|
||||
deleteConfirmMessage: 'Are you sure you want to delete "{name}"? All members will be removed. This action cannot be undone.',
|
||||
deleteSuccess: 'Space deleted',
|
||||
deleteFailed: 'Failed to delete space',
|
||||
createSuccess: 'Space created successfully',
|
||||
createFailed: 'Failed to create space',
|
||||
joinSuccess: 'Joined space successfully',
|
||||
joinFailed: 'Failed to join space',
|
||||
manageMembers: 'Manage Members',
|
||||
noMembers: 'No members',
|
||||
roleUpdated: 'Role updated',
|
||||
roleUpdateFailed: 'Failed to update role',
|
||||
memberRemoved: 'Member removed',
|
||||
memberRemoveFailed: 'Failed to remove member',
|
||||
empty: 'You have not joined any shared space yet',
|
||||
emptyDesc: 'Create a space or join an existing one with an invite code',
|
||||
all: 'All',
|
||||
createdByMe: 'Created by me',
|
||||
joinedByMe: 'Joined',
|
||||
joinedLabel: 'Joined',
|
||||
emptyCreated: 'You have not created any space yet',
|
||||
emptyCreatedDesc: 'Click "Create Space" to create one',
|
||||
emptyJoined: 'You have not joined any space yet',
|
||||
emptyJoinedDesc: 'Join an existing space with an invite code',
|
||||
role: {
|
||||
admin: 'Admin',
|
||||
editor: 'Editor',
|
||||
viewer: 'Viewer',
|
||||
},
|
||||
detail: {
|
||||
myRole: 'My Role',
|
||||
removeMemberTitle: 'Remove Member',
|
||||
removeMemberConfirm: 'Are you sure you want to remove "{name}"?',
|
||||
removeMember: 'Remove Member',
|
||||
shareKBTip: 'Go to knowledge base list, select a knowledge base and click share to share it to this space',
|
||||
},
|
||||
settings: {
|
||||
editTitle: 'Space Settings',
|
||||
detailTitle: 'Space Details',
|
||||
myRoleDesc: 'Your role in this space determines your permissions',
|
||||
membersDesc: 'View and manage space members, adjust member roles',
|
||||
sharedDesc: 'View all knowledge bases shared to this space',
|
||||
noSharedKB: 'No shared knowledge bases yet',
|
||||
noSharedKBTip: 'Knowledge base owners can share their knowledge bases to this space in KB settings',
|
||||
sharePermissionLabel: 'Space permission',
|
||||
myPermissionLabel: 'My actual permission',
|
||||
permissionCalcFormula: 'Space permission is what was set when the KB was shared to this space; my actual permission = min(space permission, my role in this space)',
|
||||
permissionCalcTip: 'My actual permission = min(space permission, my role in this space). As a viewer in the space, I have at most read-only on this KB; as editor or admin, my permission is capped by the space permission.',
|
||||
inviteMembers: 'Invite Members',
|
||||
inviteMembersDesc: 'Invite others to join the space via code or link',
|
||||
inviteLink: 'Invite Link',
|
||||
inviteLinkValidity: 'Invite link validity',
|
||||
inviteLinkValidityDesc: 'Validity period for newly generated invite links',
|
||||
validity1Day: '1 day',
|
||||
validity7Days: '7 days',
|
||||
validity30Days: '30 days',
|
||||
validityNever: 'Never expire',
|
||||
remainingValidity: 'Expires in {n} days',
|
||||
remainingValidityNever: 'Never expire',
|
||||
remainingValidityExpired: 'Expired',
|
||||
removeShareFromOrg: 'Remove from space',
|
||||
removeShareConfirm: 'Remove "{name}" from this space? Members will no longer have access to this knowledge base.',
|
||||
removeShareSuccess: 'Removed from space',
|
||||
removeShareFailed: 'Failed to remove, please try again',
|
||||
requireApproval: 'Require Approval',
|
||||
requireApprovalDesc: 'When enabled, new members need admin approval to join',
|
||||
joinRequests: 'Join Requests',
|
||||
joinRequestsDesc: 'Review pending requests to join the space',
|
||||
noPendingRequests: 'No pending requests',
|
||||
pendingJoinRequestsBadge: 'Pending join requests to review',
|
||||
pendingReview: 'Pending',
|
||||
assignRole: 'Assign role',
|
||||
approve: 'Approve',
|
||||
reject: 'Reject',
|
||||
approveSuccess: 'Request approved',
|
||||
rejectSuccess: 'Request rejected',
|
||||
reviewFailed: 'Operation failed, please try again',
|
||||
},
|
||||
editor: {
|
||||
navBasic: 'Basic Info',
|
||||
navPermissions: 'Permissions',
|
||||
navJoin: 'Join Space',
|
||||
basicTitle: 'Basic Information',
|
||||
basicDesc: 'Set the space name and description for easy identification',
|
||||
nameTip: 'Use your team or project name for easy identification',
|
||||
descriptionTip: 'Describe the purpose and goals of the space',
|
||||
permissionsTitle: 'Member Permissions',
|
||||
permissionsDesc: 'Understand the permission scope of different roles in the space',
|
||||
permissionFeature: 'Permission Feature',
|
||||
fullAccess: 'Full Access',
|
||||
editAccess: 'Edit Access',
|
||||
viewAccess: 'View Only',
|
||||
adminPerm1: 'Manage space settings, members, and knowledge base shares',
|
||||
adminPerm2: 'Share and manage knowledge bases',
|
||||
adminPerm3: 'Edit shared knowledge base content',
|
||||
adminPerm4: 'View and search knowledge bases',
|
||||
shareKBPerm: 'Share knowledge bases to space',
|
||||
editorPerm1: 'Edit shared knowledge base content',
|
||||
editorPerm2: 'View and search knowledge bases',
|
||||
editorPerm3: 'Manage space settings and members',
|
||||
viewerPerm1: 'View and search knowledge bases',
|
||||
viewerPerm2: 'Edit knowledge base content',
|
||||
viewerPerm3: 'Manage space settings',
|
||||
ownerNote: 'As the space creator, you will automatically become an admin with full permissions.',
|
||||
joinTitle: 'Join Space',
|
||||
joinDesc: 'Join an existing space with an invite code to access shared knowledge bases',
|
||||
joinIllustration: 'Enter the invite code provided by the space admin to join',
|
||||
inviteCodeTip: 'The invite code is generated by space admins, please ask them for it',
|
||||
howToGetCode: 'How to get an invite code?',
|
||||
step1: 'Contact the admin of the space you want to join',
|
||||
step2: 'Ask them to share the space invite code',
|
||||
step3: 'Paste the invite code in the input field above',
|
||||
},
|
||||
upgrade: {
|
||||
requestUpgrade: 'Request Permission Upgrade',
|
||||
pending: 'Request Submitted',
|
||||
dialogTitle: 'Request Permission Upgrade',
|
||||
currentRole: 'Current Role',
|
||||
selectRole: 'Request Role',
|
||||
reason: 'Reason (Optional)',
|
||||
reasonPlaceholder: 'Please briefly explain why you need higher permissions...',
|
||||
submitSuccess: 'Upgrade request submitted, waiting for admin approval',
|
||||
submitFailed: 'Failed to submit request',
|
||||
upgradeRequest: 'Permission Upgrade',
|
||||
},
|
||||
addMember: {
|
||||
button: 'Add Member',
|
||||
dialogTitle: 'Add Member',
|
||||
tip: 'Added users will immediately become space members and can access shared knowledge bases.',
|
||||
searchUser: 'Select User',
|
||||
searchPlaceholder: 'Search by username or email...',
|
||||
searchHint: 'Type at least 2 characters to search',
|
||||
selectRole: 'Assign Role',
|
||||
confirmBtn: 'Add',
|
||||
success: 'Member added successfully',
|
||||
failed: 'Failed to add member',
|
||||
roleHint: {
|
||||
viewer: 'Can view and search',
|
||||
editor: 'Can edit content',
|
||||
admin: 'Full management access',
|
||||
},
|
||||
},
|
||||
share: {
|
||||
title: 'Share Knowledge Base',
|
||||
selectOrg: 'Select Space',
|
||||
selectOrgPlaceholder: 'Select a space to share with',
|
||||
permission: 'Permission',
|
||||
permissionTip: 'Editable permission allows members to modify knowledge base content, Read-only permission only allows search and Q&A',
|
||||
shareSuccess: 'Knowledge base shared',
|
||||
shareFailed: 'Failed to share',
|
||||
unshareSuccess: 'Share cancelled',
|
||||
unshareFailed: 'Failed to cancel share',
|
||||
sharedTo: 'Shared to',
|
||||
noShares: 'This knowledge base has not been shared to any space',
|
||||
sharedKnowledgeBase: 'Shared Knowledge Base',
|
||||
sharedFrom: 'From',
|
||||
sharedBadge: 'Shared',
|
||||
permissionReadonly: 'Read-only',
|
||||
permissionEditable: 'Editable',
|
||||
sharedKBs: ' knowledge bases',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ export default {
|
|||
menu: {
|
||||
knowledgeBase: "知识库",
|
||||
agents: "智能体",
|
||||
organizations: "共享空间",
|
||||
chat: "对话",
|
||||
createChat: "创建对话",
|
||||
tenant: "账户信息",
|
||||
|
|
@ -18,6 +19,17 @@ export default {
|
|||
list: "知识库列表",
|
||||
fileContent: "文件内容",
|
||||
detail: "知识库详情",
|
||||
accessInfo: {
|
||||
myRole: "我的身份",
|
||||
roleOwner: "创建者",
|
||||
permissionOwner: "可编辑、管理设置、删除知识库",
|
||||
permissionAdmin: "可编辑、管理共享设置",
|
||||
permissionEditor: "可编辑文档与分类",
|
||||
permissionViewer: "仅查看与检索",
|
||||
fromOrg: "来自空间",
|
||||
sharedAt: "共享于",
|
||||
lastUpdated: "最后更新",
|
||||
},
|
||||
create: "创建知识库",
|
||||
edit: "编辑知识库",
|
||||
delete: "删除知识库",
|
||||
|
|
@ -70,6 +82,7 @@ export default {
|
|||
uploadFile: "上传文件",
|
||||
uploadFileDesc: "支持 PDF、Word、TXT 等",
|
||||
importURL: "导入网页",
|
||||
addDocument: "添加文档",
|
||||
importURLDesc: "通过URL链接导入",
|
||||
importURLTitle: "导入网页",
|
||||
manualCreate: "手动创建",
|
||||
|
|
@ -686,12 +699,14 @@ export default {
|
|||
},
|
||||
},
|
||||
common: {
|
||||
me: "我",
|
||||
confirm: "确认",
|
||||
cancel: "取消",
|
||||
save: "保存",
|
||||
delete: "删除",
|
||||
edit: "编辑",
|
||||
copy: "复制",
|
||||
copied: "已复制",
|
||||
default: "默认",
|
||||
create: "创建",
|
||||
search: "搜索",
|
||||
|
|
@ -916,6 +931,7 @@ export default {
|
|||
customSection: "我的智能体",
|
||||
addNew: "添加新智能体",
|
||||
current: "当前",
|
||||
goToSettings: "设置",
|
||||
},
|
||||
// 内置智能体信息
|
||||
builtinInfo: {
|
||||
|
|
@ -1431,17 +1447,52 @@ export default {
|
|||
create: "新建知识库",
|
||||
createFAQ: "新建 FAQ 知识库",
|
||||
subtitle: "管理和组织您的知识库,支持文档型和问答型知识库",
|
||||
myKnowledgeBases: "我的知识库",
|
||||
sharedKnowledgeBases: "共享的知识库",
|
||||
sharedToOrgs: "已共享给 {count} 个空间",
|
||||
sharedLabel: "共享",
|
||||
tabs: {
|
||||
all: "全部",
|
||||
myKnowledgeBases: "我的知识库",
|
||||
sharedToMe: "共享给我",
|
||||
},
|
||||
uninitializedBanner:
|
||||
"部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档",
|
||||
empty: {
|
||||
title: "暂无知识库",
|
||||
description: '点击左侧快捷操作"新建知识库"按钮创建第一个知识库',
|
||||
sharedTitle: "暂无共享知识库",
|
||||
sharedDescription: "您可以加入共享空间或请求他人共享知识库给您",
|
||||
},
|
||||
delete: {
|
||||
confirmTitle: "删除确认",
|
||||
confirmMessage: '确认要删除知识库"{name}"?删除后不可恢复',
|
||||
confirmButton: "确认删除",
|
||||
},
|
||||
menu: {
|
||||
viewDetails: "查看详情",
|
||||
},
|
||||
detail: {
|
||||
title: "共享知识库",
|
||||
overview: "概览",
|
||||
overviewDesc: "查看知识库基本信息和来源",
|
||||
permission: "权限",
|
||||
permissionDesc: "查看您在此知识库的操作权限",
|
||||
sourceOrg: "来源空间",
|
||||
sharedAt: "共享时间",
|
||||
myPermission: "我的权限",
|
||||
canEdit: "可以编辑知识库内容",
|
||||
canView: "可以查看知识库内容",
|
||||
canSearch: "可以搜索和使用知识库",
|
||||
goToKb: "进入知识库",
|
||||
enabled: "已启用",
|
||||
disabled: "未启用",
|
||||
},
|
||||
features: {
|
||||
knowledgeGraph: "知识图谱",
|
||||
multimodal: "多模态",
|
||||
questionGeneration: "问题生成",
|
||||
},
|
||||
messages: {
|
||||
deleted: "已删除",
|
||||
deleteFailed: "删除失败",
|
||||
|
|
@ -1482,6 +1533,7 @@ export default {
|
|||
advanced: "高级设置",
|
||||
faq: "FAQ 设置",
|
||||
graph: "知识图谱",
|
||||
share: "共享管理",
|
||||
},
|
||||
basic: {
|
||||
title: "基本信息",
|
||||
|
|
@ -1499,6 +1551,13 @@ export default {
|
|||
create: "创建知识库",
|
||||
save: "保存配置",
|
||||
},
|
||||
share: {
|
||||
description: "将知识库共享给空间,让空间成员可以访问和使用",
|
||||
addShare: "共享",
|
||||
unshareConfirm: "确定要取消对「{name}」的共享吗?",
|
||||
tip1: "共享后,空间成员将根据设定的权限访问此知识库",
|
||||
tip2: "可编辑权限允许成员修改知识库内容,只读权限仅允许检索和问答",
|
||||
},
|
||||
messages: {
|
||||
loadModelsFailed: "加载模型列表失败",
|
||||
loadDataFailed: "加载知识库数据失败",
|
||||
|
|
@ -1559,6 +1618,8 @@ export default {
|
|||
emptyDesc: '点击上方"新增 FAQ 条目"按钮开始创建',
|
||||
searchPlaceholder: "搜索问题和答案...",
|
||||
searchTest: "检索测试",
|
||||
addFaq: "添加FAQ",
|
||||
manageFaq: "FAQ操作",
|
||||
searchTestTitle: "FAQ 检索测试",
|
||||
queryLabel: "查询内容",
|
||||
queryPlaceholder: "请输入要检索的问题",
|
||||
|
|
@ -2283,4 +2344,239 @@ export default {
|
|||
},
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
title: "共享空间",
|
||||
subtitle: "创建或加入共享空间,与团队成员共享知识库",
|
||||
createOrg: "创建空间",
|
||||
joinOrg: "加入空间",
|
||||
name: "空间名称",
|
||||
namePlaceholder: "请输入空间名称",
|
||||
nameRequired: "请输入空间名称",
|
||||
avatar: "空间头像",
|
||||
description: "空间描述",
|
||||
descriptionPlaceholder: "请输入空间描述(选填)",
|
||||
noDescription: "暂无描述",
|
||||
members: "成员",
|
||||
memberCount: "成员数量",
|
||||
owner: "创建者",
|
||||
inviteCode: "邀请码",
|
||||
inviteCodePlaceholder: "请输入邀请码",
|
||||
inviteCodeRequired: "请输入邀请码",
|
||||
inviteCodeTip: "分享此邀请码给他人,他们可以通过邀请码加入空间",
|
||||
refreshInviteCode: "刷新邀请码",
|
||||
inviteCodeRefreshed: "邀请码已刷新",
|
||||
inviteCodeRefreshFailed: "刷新邀请码失败",
|
||||
join: {
|
||||
title: "加入空间",
|
||||
joining: "正在加入空间...",
|
||||
success: "成功加入空间!",
|
||||
failed: "加入空间失败",
|
||||
noCode: "未找到邀请码",
|
||||
goToOrganizations: "前往空间列表",
|
||||
confirmTitle: "确认加入空间",
|
||||
confirm: "确认加入",
|
||||
preview: "预览并加入",
|
||||
memberCount: "{count} 名成员",
|
||||
shareCount: "{count} 个共享知识库",
|
||||
alreadyMember: "您已经是该空间的成员",
|
||||
invalidCode: "无效的邀请码",
|
||||
},
|
||||
invite: {
|
||||
loading: "加载中...",
|
||||
previewTitle: "加入空间",
|
||||
previewInfo: "空间概览",
|
||||
inputDesc: "输入邀请码或粘贴邀请链接中的邀请码,查看空间信息后加入",
|
||||
previewAction: "查看",
|
||||
primaryJoin: "加入",
|
||||
invalidTitle: "无效邀请",
|
||||
invalidCode: "邀请码无效或已过期",
|
||||
previewFailed: "预览失败,请稍后重试",
|
||||
members: "成员",
|
||||
knowledgeBases: "知识库",
|
||||
alreadyMember: "您已经是该空间的成员",
|
||||
confirmJoin: "确认加入",
|
||||
submitRequest: "申请加入",
|
||||
requireApprovalTip: "该空间需要管理员审核后才能加入",
|
||||
approvalLabel: "加入方式",
|
||||
needApproval: "需要审核",
|
||||
noApproval: "无需审核",
|
||||
defaultRoleAfterJoin: "加入后默认权限:{role}",
|
||||
requestRole: "申请角色",
|
||||
selectRole: "选择角色",
|
||||
messagePlaceholder: "选填:申请说明(如自我介绍或加入原因)",
|
||||
joinSuccess: "成功加入空间!",
|
||||
joinFailed: "加入失败,请稍后重试",
|
||||
requestSubmitted: "申请已提交,请等待管理员审核",
|
||||
requestFailed: "申请提交失败,请稍后重试",
|
||||
viewOrganization: "查看空间",
|
||||
},
|
||||
leave: "退出空间",
|
||||
leaveConfirm: "确定要退出该空间吗?",
|
||||
leaveConfirmTitle: "退出空间",
|
||||
leaveConfirmMessage: "确定要退出空间「{name}」吗?退出后将无法访问该空间共享的知识库。",
|
||||
leaveSuccess: "已退出空间",
|
||||
leaveFailed: "退出空间失败",
|
||||
deleteConfirm: "确定要删除该空间吗?此操作不可撤销。",
|
||||
deleteConfirmTitle: "删除空间",
|
||||
deleteConfirmMessage: "确定要删除空间「{name}」吗?删除后所有成员将被移除,此操作不可撤销。",
|
||||
deleteSuccess: "空间已删除",
|
||||
deleteFailed: "删除空间失败",
|
||||
createSuccess: "空间创建成功",
|
||||
createFailed: "创建空间失败",
|
||||
joinSuccess: "成功加入空间",
|
||||
joinFailed: "加入空间失败",
|
||||
manageMembers: "成员管理",
|
||||
noMembers: "暂无成员",
|
||||
roleUpdated: "角色已更新",
|
||||
roleUpdateFailed: "更新角色失败",
|
||||
memberRemoved: "成员已移除",
|
||||
memberRemoveFailed: "移除成员失败",
|
||||
empty: "您还没有加入任何共享空间",
|
||||
emptyDesc: "创建一个空间或通过邀请码加入现有空间",
|
||||
all: "全部",
|
||||
createdByMe: "我创建的",
|
||||
joinedByMe: "我加入的",
|
||||
joinedLabel: "已加入",
|
||||
emptyCreated: "您还没有创建任何共享空间",
|
||||
emptyCreatedDesc: "点击「创建空间」创建一个新空间",
|
||||
emptyJoined: "您还没有加入任何共享空间",
|
||||
emptyJoinedDesc: "通过邀请码加入现有空间",
|
||||
role: {
|
||||
admin: "管理员",
|
||||
editor: "编辑",
|
||||
viewer: "只读",
|
||||
},
|
||||
detail: {
|
||||
myRole: "我的角色",
|
||||
removeMemberTitle: "移除成员",
|
||||
removeMemberConfirm: "确定要移除成员「{name}」吗?",
|
||||
removeMember: "移除成员",
|
||||
shareKBTip: "在知识库列表中选择知识库,点击共享按钮将其共享到此空间",
|
||||
},
|
||||
settings: {
|
||||
editTitle: "空间设置",
|
||||
detailTitle: "空间详情",
|
||||
myRoleDesc: "您在此空间中的角色决定了您的权限范围",
|
||||
membersDesc: "查看和管理空间成员,调整成员角色",
|
||||
sharedDesc: "查看共享到此空间的所有知识库",
|
||||
noSharedKB: "暂无共享的知识库",
|
||||
noSharedKBTip: "知识库拥有者可以在知识库设置中将其共享到此空间",
|
||||
sharePermissionLabel: "空间权限",
|
||||
myPermissionLabel: "我的实际权限",
|
||||
permissionCalcFormula: "空间权限为共享时给该空间设定的权限;我的实际权限 = min(空间权限, 我在本空间的角色)",
|
||||
permissionCalcTip: "我的实际权限 = min(空间权限, 我在本空间的角色)。我在空间内是只读时,对此知识库最多只读;是编辑或管理员时,不超过空间权限。",
|
||||
inviteMembers: "邀请成员",
|
||||
inviteMembersDesc: "通过邀请码或链接邀请他人加入空间",
|
||||
inviteLink: "邀请链接",
|
||||
inviteLinkValidity: "邀请链接有效期",
|
||||
inviteLinkValidityDesc: "新生成的邀请链接的有效期,仅影响之后刷新生成的链接",
|
||||
validity1Day: "1 天",
|
||||
validity7Days: "7 天",
|
||||
validity30Days: "30 天",
|
||||
validityNever: "永不过期",
|
||||
remainingValidity: "剩余 {n} 天",
|
||||
remainingValidityNever: "永不过期",
|
||||
remainingValidityExpired: "已过期",
|
||||
removeShareFromOrg: "从空间中移除",
|
||||
removeShareConfirm: "确定将「{name}」从本空间中移除?移除后空间成员将无法再访问该知识库。",
|
||||
removeShareSuccess: "已从空间中移除",
|
||||
removeShareFailed: "移除失败,请重试",
|
||||
requireApproval: "需要审核",
|
||||
requireApprovalDesc: "开启后,新成员加入需要管理员审核",
|
||||
joinRequests: "加入申请",
|
||||
joinRequestsDesc: "审核待加入空间的申请",
|
||||
noPendingRequests: "暂无待审核的申请",
|
||||
pendingJoinRequestsBadge: "有待审批的加入申请",
|
||||
pendingReview: "待审批",
|
||||
assignRole: "分配角色",
|
||||
approve: "通过",
|
||||
reject: "拒绝",
|
||||
approveSuccess: "已通过申请",
|
||||
rejectSuccess: "已拒绝申请",
|
||||
reviewFailed: "操作失败,请重试",
|
||||
},
|
||||
editor: {
|
||||
navBasic: "基本信息",
|
||||
navPermissions: "权限说明",
|
||||
navJoin: "加入空间",
|
||||
basicTitle: "基本信息",
|
||||
basicDesc: "设置空间的名称和描述,便于成员识别",
|
||||
nameTip: "建议使用团队或项目名称,便于成员识别",
|
||||
descriptionTip: "描述空间的用途和目标,帮助成员了解空间",
|
||||
permissionsTitle: "成员权限",
|
||||
permissionsDesc: "了解空间中不同角色的权限范围",
|
||||
permissionFeature: "权限功能",
|
||||
fullAccess: "完整权限",
|
||||
editAccess: "编辑权限",
|
||||
viewAccess: "只读权限",
|
||||
adminPerm1: "管理空间设置、成员及知识库共享",
|
||||
adminPerm2: "共享和管理知识库",
|
||||
adminPerm3: "编辑共享知识库内容",
|
||||
adminPerm4: "查看和检索知识库",
|
||||
shareKBPerm: "共享知识库到空间",
|
||||
editorPerm1: "编辑共享知识库内容",
|
||||
editorPerm2: "查看和检索知识库",
|
||||
editorPerm3: "管理空间设置和成员",
|
||||
viewerPerm1: "查看和检索知识库",
|
||||
viewerPerm2: "编辑知识库内容",
|
||||
viewerPerm3: "管理空间设置",
|
||||
ownerNote: "作为空间创建者,您将自动成为空间的管理员,拥有完整权限。",
|
||||
joinTitle: "加入空间",
|
||||
joinDesc: "通过邀请码加入现有空间,获得知识库访问权限",
|
||||
joinIllustration: "输入空间管理员提供的邀请码即可加入",
|
||||
inviteCodeTip: "邀请码由空间管理员生成,请向他们索取",
|
||||
howToGetCode: "如何获取邀请码?",
|
||||
step1: "联系您要加入的空间管理员",
|
||||
step2: "请求他们分享空间邀请码",
|
||||
step3: "将邀请码粘贴到上方输入框",
|
||||
},
|
||||
upgrade: {
|
||||
requestUpgrade: "申请权限升级",
|
||||
pending: "已提交申请",
|
||||
dialogTitle: "申请权限升级",
|
||||
currentRole: "当前角色",
|
||||
selectRole: "申请角色",
|
||||
reason: "申请理由(选填)",
|
||||
reasonPlaceholder: "请简要说明申请更高权限的原因...",
|
||||
submitSuccess: "权限升级申请已提交,等待管理员审核",
|
||||
submitFailed: "提交申请失败",
|
||||
upgradeRequest: "权限升级",
|
||||
},
|
||||
addMember: {
|
||||
button: "添加成员",
|
||||
dialogTitle: "添加成员",
|
||||
tip: "添加的用户将立即成为空间成员,可以访问空间内共享的知识库。",
|
||||
searchUser: "选择用户",
|
||||
searchPlaceholder: "输入用户名或邮箱搜索...",
|
||||
searchHint: "输入至少2个字符开始搜索",
|
||||
selectRole: "分配角色",
|
||||
confirmBtn: "添加",
|
||||
success: "成员添加成功",
|
||||
failed: "添加失败",
|
||||
roleHint: {
|
||||
viewer: "可查看和搜索",
|
||||
editor: "可编辑内容",
|
||||
admin: "完整管理权限",
|
||||
},
|
||||
},
|
||||
share: {
|
||||
title: "共享知识库",
|
||||
selectOrg: "选择空间",
|
||||
selectOrgPlaceholder: "请选择要共享的空间",
|
||||
permission: "权限",
|
||||
permissionTip: "可编辑权限允许成员修改知识库内容,只读权限仅允许检索和问答",
|
||||
shareSuccess: "知识库已共享",
|
||||
shareFailed: "共享失败",
|
||||
unshareSuccess: "已取消共享",
|
||||
unshareFailed: "取消共享失败",
|
||||
sharedTo: "已共享到",
|
||||
noShares: "该知识库尚未共享到任何空间",
|
||||
sharedKnowledgeBase: "共享知识库",
|
||||
sharedFrom: "来自",
|
||||
sharedBadge: "共享",
|
||||
permissionReadonly: "只读",
|
||||
permissionEditable: "可编辑",
|
||||
sharedKBs: "个知识库",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -16,6 +16,19 @@ const router = createRouter({
|
|||
component: () => import("../views/auth/Login.vue"),
|
||||
meta: { requiresAuth: false, requiresInit: false }
|
||||
},
|
||||
{
|
||||
path: "/join",
|
||||
name: "joinOrganization",
|
||||
// 重定向到组织列表页,并将 code 参数转换为 invite_code
|
||||
redirect: (to) => {
|
||||
const code = to.query.code as string
|
||||
return {
|
||||
path: '/platform/organizations',
|
||||
query: code ? { invite_code: code } : {}
|
||||
}
|
||||
},
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
{
|
||||
path: "/knowledgeBase",
|
||||
name: "home",
|
||||
|
|
@ -75,6 +88,12 @@ const router = createRouter({
|
|||
component: () => import("../views/chat/index.vue"),
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
{
|
||||
path: "organizations",
|
||||
name: "organizationList",
|
||||
component: () => import("../views/organization/OrganizationList.vue"),
|
||||
meta: { requiresInit: true, requiresAuth: true }
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ export const useMenuStore = defineStore('menuStore', () => {
|
|||
const menuArr = reactive<MenuItem[]>([
|
||||
{ title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },
|
||||
{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents' },
|
||||
{ title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations' },
|
||||
{
|
||||
title: '',
|
||||
titleKey: 'menu.chat',
|
||||
|
|
@ -54,14 +55,14 @@ export const useMenuStore = defineStore('menuStore', () => {
|
|||
)
|
||||
|
||||
const clearMenuArr = () => {
|
||||
const chatMenu = menuArr[2]
|
||||
const chatMenu = menuArr[3]
|
||||
if (chatMenu && chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
}
|
||||
|
||||
const updatemenuArr = (obj: any) => {
|
||||
const chatMenu = menuArr[2]
|
||||
const chatMenu = menuArr[3]
|
||||
if (!chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
|
|
@ -72,7 +73,7 @@ export const useMenuStore = defineStore('menuStore', () => {
|
|||
}
|
||||
|
||||
const updataMenuChildren = (item: MenuChild) => {
|
||||
const chatMenu = menuArr[2]
|
||||
const chatMenu = menuArr[3]
|
||||
if (!chatMenu.children) {
|
||||
chatMenu.children = createMenuChildren()
|
||||
}
|
||||
|
|
@ -80,7 +81,7 @@ export const useMenuStore = defineStore('menuStore', () => {
|
|||
}
|
||||
|
||||
const updatasessionTitle = (sessionId: string, title: string) => {
|
||||
const chatMenu = menuArr[2]
|
||||
const chatMenu = menuArr[3]
|
||||
chatMenu.children?.forEach((item: MenuChild) => {
|
||||
if (item.id === sessionId) {
|
||||
item.title = title
|
||||
|
|
|
|||
|
|
@ -0,0 +1,435 @@
|
|||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type {
|
||||
Organization,
|
||||
OrganizationMember,
|
||||
SharedKnowledgeBase,
|
||||
OrganizationPreview
|
||||
} from '@/api/organization'
|
||||
import {
|
||||
listMyOrganizations,
|
||||
createOrganization,
|
||||
updateOrganization,
|
||||
deleteOrganization,
|
||||
joinOrganization,
|
||||
previewOrganization,
|
||||
leaveOrganization,
|
||||
generateInviteCode,
|
||||
listMembers,
|
||||
updateMemberRole,
|
||||
removeMember,
|
||||
listSharedKnowledgeBases
|
||||
} from '@/api/organization'
|
||||
|
||||
export const useOrganizationStore = defineStore('organization', () => {
|
||||
// State
|
||||
const organizations = ref<Organization[]>([])
|
||||
const currentOrganization = ref<Organization | null>(null)
|
||||
const currentMembers = ref<OrganizationMember[]>([])
|
||||
const sharedKnowledgeBases = ref<SharedKnowledgeBase[]>([])
|
||||
const previewData = ref<OrganizationPreview | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Computed
|
||||
const myOrganizations = computed(() => organizations.value)
|
||||
|
||||
const ownedOrganizations = computed(() =>
|
||||
organizations.value.filter(org => org.is_owner)
|
||||
)
|
||||
|
||||
const joinedOrganizations = computed(() =>
|
||||
organizations.value.filter(org => !org.is_owner)
|
||||
)
|
||||
|
||||
/** 当前用户作为管理员/创建者可见的待审批加入申请总数(用于侧栏提醒) */
|
||||
const totalPendingJoinRequestCount = computed(() =>
|
||||
organizations.value.reduce((sum, org) => sum + (org.pending_join_request_count ?? 0), 0)
|
||||
)
|
||||
|
||||
// Actions
|
||||
|
||||
/**
|
||||
* Fetch all organizations the user belongs to
|
||||
*/
|
||||
async function fetchOrganizations() {
|
||||
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'
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch organizations'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new organization
|
||||
*/
|
||||
async function create(name: string, description?: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await createOrganization({ name, description })
|
||||
if (response.success && response.data) {
|
||||
organizations.value.unshift(response.data)
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to create organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to create organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an organization
|
||||
*/
|
||||
async function update(id: string, name?: string, description?: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await updateOrganization(id, { name, description })
|
||||
if (response.success && response.data) {
|
||||
const index = organizations.value.findIndex(o => o.id === id)
|
||||
if (index !== -1) {
|
||||
organizations.value[index] = response.data
|
||||
}
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = response.data
|
||||
}
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to update organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to update organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an organization
|
||||
*/
|
||||
async function remove(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await deleteOrganization(id)
|
||||
if (response.success) {
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to delete organization'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to delete organization'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview an organization by invite code (without joining)
|
||||
*/
|
||||
async function preview(inviteCode: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
previewData.value = null
|
||||
try {
|
||||
const response = await previewOrganization(inviteCode)
|
||||
if (response.success && response.data) {
|
||||
previewData.value = response.data
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to preview organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to preview organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an organization by invite code
|
||||
*/
|
||||
async function join(inviteCode: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await joinOrganization({ invite_code: inviteCode })
|
||||
if (response.success && response.data) {
|
||||
// Check if already in list
|
||||
const exists = organizations.value.some(o => o.id === response.data!.id)
|
||||
if (!exists) {
|
||||
organizations.value.unshift(response.data)
|
||||
}
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to join organization'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to join organization'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave an organization
|
||||
*/
|
||||
async function leave(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await leaveOrganization(id)
|
||||
if (response.success) {
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to leave organization'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to leave organization'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new invite code
|
||||
*/
|
||||
async function refreshInviteCode(id: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await generateInviteCode(id)
|
||||
if (response.success && response.data) {
|
||||
const org = organizations.value.find(o => o.id === id)
|
||||
if (org) {
|
||||
org.invite_code = response.data.invite_code
|
||||
}
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value.invite_code = response.data.invite_code
|
||||
}
|
||||
return response.data.invite_code
|
||||
} else {
|
||||
error.value = response.message || 'Failed to generate invite code'
|
||||
return null
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to generate invite code'
|
||||
return null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch members of an organization
|
||||
*/
|
||||
async function fetchMembers(orgId: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await listMembers(orgId)
|
||||
if (response.success && response.data) {
|
||||
currentMembers.value = response.data.members
|
||||
return response.data.members
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch members'
|
||||
return []
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch members'
|
||||
return []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a member's role
|
||||
*/
|
||||
async function changeMemberRole(orgId: string, userId: string, role: 'admin' | 'editor' | 'viewer') {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await updateMemberRole(orgId, userId, { role })
|
||||
if (response.success) {
|
||||
const member = currentMembers.value.find(m => m.user_id === userId)
|
||||
if (member) {
|
||||
member.role = role
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to update member role'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to update member role'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a member from organization
|
||||
*/
|
||||
async function kickMember(orgId: string, userId: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await removeMember(orgId, userId)
|
||||
if (response.success) {
|
||||
currentMembers.value = currentMembers.value.filter(m => m.user_id !== userId)
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to remove member'
|
||||
return false
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to remove member'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch shared knowledge bases
|
||||
*/
|
||||
async function fetchSharedKnowledgeBases() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await listSharedKnowledgeBases()
|
||||
if (response.success && response.data) {
|
||||
// Filter out shares whose knowledge_base was deleted (null)
|
||||
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
|
||||
return sharedKnowledgeBases.value
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch shared knowledge bases'
|
||||
return []
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch shared knowledge bases'
|
||||
return []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current organization for detail view
|
||||
*/
|
||||
function setCurrentOrganization(org: Organization | null) {
|
||||
currentOrganization.value = org
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user's permission for a specific knowledge base
|
||||
* Returns 'owner' if user owns the KB, or the share permission ('admin' | 'editor' | 'viewer'), or null if no access
|
||||
*/
|
||||
function getKBPermission(kbId: string): 'owner' | 'admin' | 'editor' | 'viewer' | null {
|
||||
const shared = sharedKnowledgeBases.value.find(
|
||||
s => s.knowledge_base?.id === kbId
|
||||
)
|
||||
return shared?.permission || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user can edit a knowledge base (owner, admin, or editor)
|
||||
*/
|
||||
function canEditKB(kbId: string, isOwner: boolean): boolean {
|
||||
if (isOwner) return true
|
||||
const permission = getKBPermission(kbId)
|
||||
return permission === 'admin' || permission === 'editor'
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user can delete/manage a knowledge base (owner or admin only)
|
||||
*/
|
||||
function canManageKB(kbId: string, isOwner: boolean): boolean {
|
||||
if (isOwner) return true
|
||||
const permission = getKBPermission(kbId)
|
||||
return permission === 'admin'
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all state
|
||||
*/
|
||||
function clearState() {
|
||||
organizations.value = []
|
||||
currentOrganization.value = null
|
||||
currentMembers.value = []
|
||||
sharedKnowledgeBases.value = []
|
||||
previewData.value = null
|
||||
error.value = null
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
organizations,
|
||||
currentOrganization,
|
||||
currentMembers,
|
||||
sharedKnowledgeBases,
|
||||
previewData,
|
||||
loading,
|
||||
error,
|
||||
|
||||
// Computed
|
||||
myOrganizations,
|
||||
ownedOrganizations,
|
||||
joinedOrganizations,
|
||||
totalPendingJoinRequestCount,
|
||||
|
||||
// Actions
|
||||
fetchOrganizations,
|
||||
create,
|
||||
update,
|
||||
remove,
|
||||
preview,
|
||||
join,
|
||||
leave,
|
||||
refreshInviteCode,
|
||||
fetchMembers,
|
||||
changeMemberRole,
|
||||
kickMember,
|
||||
fetchSharedKnowledgeBases,
|
||||
setCurrentOrganization,
|
||||
getKBPermission,
|
||||
canEditKB,
|
||||
canManageKB,
|
||||
clearState
|
||||
}
|
||||
})
|
||||
|
|
@ -6,6 +6,20 @@
|
|||
<h2>{{ $t('agent.title') }}</h2>
|
||||
<p class="header-subtitle">{{ $t('agent.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<t-button class="agent-create-btn" @click="handleCreateAgent">
|
||||
<template #icon>
|
||||
<span class="btn-icon-wrapper">
|
||||
<svg class="sparkles-icon" width="18" height="18" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10 3L10.8 6.2C10.9 6.7 11.3 7.1 11.8 7.2L15 8L11.8 8.8C11.3 8.9 10.9 9.3 10.8 9.8L10 13L9.2 9.8C9.1 9.3 8.7 8.9 8.2 8.8L5 8L8.2 7.2C8.7 7.1 9.1 6.7 9.2 6.2L10 3Z" fill="currentColor" stroke="currentColor" stroke-width="0.8" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M15.5 4L15.8 5.2C15.85 5.45 16.05 5.65 16.3 5.7L17.5 6L16.3 6.3C16.05 6.35 15.85 6.55 15.8 6.8L15.5 8L15.2 6.8C15.15 6.55 14.95 6.35 14.7 6.3L13.5 6L14.7 5.7C14.95 5.65 15.15 5.45 15.2 5.2L15.5 4Z" fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M4.5 13L4.8 14.2C4.85 14.45 5.05 14.65 5.3 14.7L6.5 15L5.3 15.3C5.05 15.35 4.85 15.55 4.8 15.8L4.5 17L4.2 15.8C4.15 15.55 3.95 15.35 3.7 15.3L2.5 15L3.7 14.7C3.95 14.65 4.15 14.45 4.2 14.2L4.5 13Z" fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
<span>{{ $t('agent.createAgent') }}</span>
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-divider"></div>
|
||||
|
||||
|
|
@ -323,6 +337,11 @@ const openCreateModal = () => {
|
|||
editorVisible.value = true
|
||||
}
|
||||
|
||||
// 创建智能体
|
||||
const handleCreateAgent = () => {
|
||||
openCreateModal()
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
openCreateModal
|
||||
})
|
||||
|
|
@ -358,6 +377,76 @@ defineExpose({
|
|||
font-weight: 600;
|
||||
line-height: 32px;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
|
||||
:deep(.agent-create-btn) {
|
||||
--ripple-color: rgba(118, 75, 162, 0.3) !important;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
|
||||
border: none !important;
|
||||
color: #fff !important;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
&:hover,
|
||||
&:active,
|
||||
&:focus,
|
||||
&.t-is-active,
|
||||
&[data-state="active"] {
|
||||
background: linear-gradient(135deg, #5a6fd6 0%, #6a4190 100%) !important;
|
||||
border: none !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
// 覆盖 TDesign 按钮的 CSS 变量
|
||||
--td-button-primary-bg-color: #667eea !important;
|
||||
--td-button-primary-border-color: #667eea !important;
|
||||
--td-button-primary-active-bg-color: #5a6fd6 !important;
|
||||
--td-button-primary-active-border-color: #5a6fd6 !important;
|
||||
}
|
||||
|
||||
.agent-create-btn {
|
||||
.btn-icon-wrapper {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.sparkles-icon {
|
||||
animation: twinkle 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -50%;
|
||||
left: -50%;
|
||||
width: 200%;
|
||||
height: 200%;
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
transparent 30%,
|
||||
rgba(255, 255, 255, 0.1) 50%,
|
||||
transparent 70%
|
||||
);
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.6s ease;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
&:hover::before {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes twinkle {
|
||||
0%, 100% { opacity: 1; transform: scale(1); }
|
||||
50% { opacity: 0.8; transform: scale(0.95); }
|
||||
}
|
||||
}
|
||||
|
||||
.header-subtitle {
|
||||
|
|
|
|||
|
|
@ -320,9 +320,22 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => {
|
|||
const webSearchEnabled = useSettingsStoreInstance.isWebSearchEnabled;
|
||||
|
||||
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
|
||||
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
|
||||
const knowledgeIds = useSettingsStoreInstance.settings.selectedFiles || [];
|
||||
|
||||
// Merge @mentioned KB/file IDs so retrieval uses the same targets user @mentioned (including shared KBs)
|
||||
const sidebarKbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
|
||||
const sidebarFileIds = useSettingsStoreInstance.settings.selectedFiles || [];
|
||||
const kbIdSet = new Set(sidebarKbIds);
|
||||
const fileIdSet = new Set(sidebarFileIds);
|
||||
for (const item of mentionedItems || []) {
|
||||
if (!item?.id) continue;
|
||||
if (item.type === 'kb' && !kbIdSet.has(item.id)) {
|
||||
kbIdSet.add(item.id);
|
||||
} else if (item.type === 'file' && !fileIdSet.has(item.id)) {
|
||||
fileIdSet.add(item.id);
|
||||
}
|
||||
}
|
||||
const kbIds = [...kbIdSet];
|
||||
const knowledgeIds = [...fileIdSet];
|
||||
|
||||
// Get selected agent ID
|
||||
const selectedAgentId = useSettingsStoreInstance.selectedAgentId || '';
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,13 @@ import EmptyKnowledge from '@/components/empty-knowledge.vue';
|
|||
import { getSessionsList, createSessions, generateSessionsTitle } from "@/api/chat/index";
|
||||
import { useMenuStore } from '@/stores/menu';
|
||||
import { useUIStore } from '@/stores/ui';
|
||||
import { useOrganizationStore } from '@/stores/organization';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue';
|
||||
const usemenuStore = useMenuStore();
|
||||
const uiStore = useUIStore();
|
||||
const orgStore = useOrganizationStore();
|
||||
const authStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
import {
|
||||
batchQueryKnowledge,
|
||||
|
|
@ -32,9 +36,59 @@ const { t } = useI18n();
|
|||
const kbId = computed(() => (route.params as any).kbId as string || '');
|
||||
const kbInfo = ref<any>(null);
|
||||
const uploadInputRef = ref<HTMLInputElement | null>(null);
|
||||
const folderUploadInputRef = ref<HTMLInputElement | null>(null);
|
||||
const uploading = ref(false);
|
||||
const kbLoading = ref(false);
|
||||
const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq');
|
||||
|
||||
// Permission control: check if current user owns this KB or has edit/manage permission
|
||||
const isOwner = computed(() => {
|
||||
if (!kbInfo.value) return false;
|
||||
// Check if the current user's tenant ID matches the KB's tenant ID
|
||||
const userTenantId = authStore.effectiveTenantId;
|
||||
return kbInfo.value.tenant_id === userTenantId;
|
||||
});
|
||||
|
||||
// Can edit: owner, admin, or editor
|
||||
const canEdit = computed(() => {
|
||||
return orgStore.canEditKB(kbId.value, isOwner.value);
|
||||
});
|
||||
|
||||
// Can manage (delete, settings, etc.): owner or admin
|
||||
const canManage = computed(() => {
|
||||
return orgStore.canManageKB(kbId.value, isOwner.value);
|
||||
});
|
||||
|
||||
// Current KB's shared record (when accessed via organization share)
|
||||
const currentSharedKb = computed(() =>
|
||||
orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === kbId.value) ?? null,
|
||||
);
|
||||
|
||||
// Display role label: owner or org role (admin/editor/viewer)
|
||||
const accessRoleLabel = computed(() => {
|
||||
if (isOwner.value) return t('knowledgeBase.accessInfo.roleOwner');
|
||||
const perm = orgStore.getKBPermission(kbId.value);
|
||||
if (perm) return t(`organization.role.${perm}`);
|
||||
return '--';
|
||||
});
|
||||
|
||||
// Permission summary text for current role
|
||||
const accessPermissionSummary = computed(() => {
|
||||
if (isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner');
|
||||
const perm = orgStore.getKBPermission(kbId.value);
|
||||
if (perm === 'admin') return t('knowledgeBase.accessInfo.permissionAdmin');
|
||||
if (perm === 'editor') return t('knowledgeBase.accessInfo.permissionEditor');
|
||||
if (perm === 'viewer') return t('knowledgeBase.accessInfo.permissionViewer');
|
||||
return '--';
|
||||
});
|
||||
|
||||
// Last updated time from kbInfo
|
||||
const kbLastUpdated = computed(() => {
|
||||
const raw = kbInfo.value?.updated_at;
|
||||
if (!raw) return null;
|
||||
return formatStringDate(new Date(raw));
|
||||
});
|
||||
|
||||
const knowledgeList = ref<Array<{ id: string; name: string; type?: string }>>([]);
|
||||
let { cardList, total, moreIndex, details, getKnowled, delKnowledge, openMore, onVisibleChange, getCardDetails, getfDetails } = useKnowledgeBase(kbId.value)
|
||||
let isCardDetails = ref(false);
|
||||
|
|
@ -397,11 +451,26 @@ const loadKnowledgeBaseInfo = async (targetKbId: string) => {
|
|||
const loadKnowledgeList = async () => {
|
||||
try {
|
||||
const res: any = await listKnowledgeBases();
|
||||
knowledgeList.value = (res?.data || []).map((item: any) => ({
|
||||
const myKbs = (res?.data || []).map((item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.name,
|
||||
type: item.type || 'document',
|
||||
}));
|
||||
|
||||
// Also include shared knowledge bases from orgStore
|
||||
const sharedKbs = (orgStore.sharedKnowledgeBases || [])
|
||||
.filter(s => s.knowledge_base != null)
|
||||
.map(s => ({
|
||||
id: String(s.knowledge_base.id),
|
||||
name: s.knowledge_base.name,
|
||||
type: s.knowledge_base.type || 'document',
|
||||
}));
|
||||
|
||||
// Merge and deduplicate by id (my KBs take precedence)
|
||||
const myKbIds = new Set(myKbs.map(kb => kb.id));
|
||||
const uniqueSharedKbs = sharedKbs.filter(kb => !myKbIds.has(kb.id));
|
||||
|
||||
knowledgeList.value = [...myKbs, ...uniqueSharedKbs];
|
||||
} catch (error) {
|
||||
console.error('Failed to load knowledge list:', error);
|
||||
}
|
||||
|
|
@ -485,7 +554,9 @@ const handleOpenURLImportDialog = (event: CustomEvent) => {
|
|||
onMounted(() => {
|
||||
loadKnowledgeBaseInfo(kbId.value);
|
||||
loadKnowledgeList();
|
||||
|
||||
// Load shared knowledge bases to get permission info
|
||||
orgStore.fetchSharedKnowledgeBases();
|
||||
|
||||
// 监听文件上传事件
|
||||
window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
|
||||
// 监听URL导入对话框打开事件
|
||||
|
|
@ -587,6 +658,32 @@ const documentTitle = computed(() => {
|
|||
return t('knowledgeEditor.document.title');
|
||||
});
|
||||
|
||||
// 文档操作下拉菜单选项
|
||||
const documentActionOptions = computed(() => [
|
||||
{ content: t('upload.uploadDocument'), value: 'upload', prefixIcon: () => h(TIcon, { name: 'upload', size: '16px' }) },
|
||||
{ content: t('upload.uploadFolder'), value: 'uploadFolder', prefixIcon: () => h(TIcon, { name: 'folder-add', size: '16px' }) },
|
||||
{ content: t('knowledgeBase.importURL'), value: 'importURL', prefixIcon: () => h(TIcon, { name: 'link', size: '16px' }) },
|
||||
{ content: t('upload.onlineEdit'), value: 'manualCreate', prefixIcon: () => h(TIcon, { name: 'edit', size: '16px' }) },
|
||||
]);
|
||||
|
||||
// 处理文档操作下拉菜单选择
|
||||
const handleDocumentActionSelect = (data: { value: string }) => {
|
||||
switch (data.value) {
|
||||
case 'upload':
|
||||
handleDocumentUploadClick();
|
||||
break;
|
||||
case 'uploadFolder':
|
||||
handleFolderUploadClick();
|
||||
break;
|
||||
case 'importURL':
|
||||
handleURLImportClick();
|
||||
break;
|
||||
case 'manualCreate':
|
||||
handleManualCreate();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const ensureDocumentKbReady = () => {
|
||||
if (isFAQ.value) {
|
||||
MessagePlugin.warning('当前知识库类型不支持该操作');
|
||||
|
|
@ -609,6 +706,11 @@ const handleDocumentUploadClick = () => {
|
|||
uploadInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handleFolderUploadClick = () => {
|
||||
if (!ensureDocumentKbReady()) return;
|
||||
folderUploadInputRef.value?.click();
|
||||
};
|
||||
|
||||
const resetUploadInput = () => {
|
||||
if (uploadInputRef.value) {
|
||||
uploadInputRef.value.value = '';
|
||||
|
|
@ -705,6 +807,102 @@ const handleDocumentUpload = async (event: Event) => {
|
|||
resetUploadInput();
|
||||
};
|
||||
|
||||
// 处理文件夹上传
|
||||
const handleFolderUpload = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = input?.files;
|
||||
if (!files || files.length === 0) return;
|
||||
|
||||
if (!kbId.value) {
|
||||
MessagePlugin.error("缺少知识库ID");
|
||||
if (input) input.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否启用了VLM
|
||||
const vlmEnabled = kbInfo.value?.vlm_config?.enabled || false;
|
||||
|
||||
// 过滤有效文件
|
||||
const validFiles: File[] = [];
|
||||
let hiddenFileCount = 0;
|
||||
let imageFilteredCount = 0;
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i];
|
||||
const relativePath = (file as any).webkitRelativePath || file.name;
|
||||
|
||||
// 1. 过滤隐藏文件和隐藏文件夹
|
||||
const pathParts = relativePath.split('/');
|
||||
const hasHiddenComponent = pathParts.some((part: string) => part.startsWith('.'));
|
||||
if (hasHiddenComponent) {
|
||||
hiddenFileCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. 如果未启用VLM,过滤图片文件
|
||||
if (!vlmEnabled) {
|
||||
const fileExt = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
|
||||
const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
|
||||
if (imageTypes.includes(fileExt)) {
|
||||
imageFilteredCount++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 文件类型验证
|
||||
if (!kbFileTypeVerification(file, true)) {
|
||||
validFiles.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (validFiles.length === 0) {
|
||||
MessagePlugin.warning(t('knowledgeBase.noValidFilesInFolder', { total: files.length }));
|
||||
if (input) input.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
MessagePlugin.info(t('knowledgeBase.uploadingFolder', { total: validFiles.length }));
|
||||
|
||||
// 批量上传
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
const tagIdToUpload = selectedTagId.value !== '__untagged__' ? selectedTagId.value : undefined;
|
||||
|
||||
for (const file of validFiles) {
|
||||
const relativePath = (file as any).webkitRelativePath;
|
||||
let fileName = file.name;
|
||||
if (relativePath) {
|
||||
const pathParts = relativePath.split('/');
|
||||
if (pathParts.length > 2) {
|
||||
const subPath = pathParts.slice(1, -1).join('/');
|
||||
fileName = `${subPath}/${file.name}`;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await uploadKnowledgeFile(kbId.value, { file, fileName, tag_id: tagIdToUpload });
|
||||
successCount++;
|
||||
} catch (error: any) {
|
||||
failCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (successCount > 0) {
|
||||
window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', {
|
||||
detail: { kbId: kbId.value }
|
||||
}));
|
||||
}
|
||||
|
||||
if (failCount === 0) {
|
||||
MessagePlugin.success(t('knowledgeBase.uploadAllSuccess', { count: successCount }));
|
||||
} else if (successCount > 0) {
|
||||
MessagePlugin.warning(t('knowledgeBase.uploadPartialSuccess', { success: successCount, fail: failCount }));
|
||||
} else {
|
||||
MessagePlugin.error(t('knowledgeBase.uploadAllFailed'));
|
||||
}
|
||||
|
||||
if (input) input.value = '';
|
||||
};
|
||||
|
||||
const handleManualCreate = () => {
|
||||
if (!ensureDocumentKbReady()) return;
|
||||
|
|
@ -939,7 +1137,7 @@ async function createNewSession(value: string): Promise<void> {
|
|||
<t-icon name="chevron-right" class="breadcrumb-separator" />
|
||||
<span class="breadcrumb-current">{{ $t('knowledgeEditor.document.title') }}</span>
|
||||
</h2>
|
||||
<t-tooltip :content="$t('knowledgeBase.settings')" placement="top">
|
||||
<t-tooltip v-if="canManage" :content="$t('knowledgeBase.settings')" placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="kb-settings-button"
|
||||
|
|
@ -951,6 +1149,41 @@ async function createNewSession(value: string): Promise<void> {
|
|||
</t-tooltip>
|
||||
</div>
|
||||
<p class="document-subtitle">{{ $t('knowledgeEditor.document.subtitle') }}</p>
|
||||
<!-- 当前知识库权限与来源信息 -->
|
||||
<div v-if="kbInfo" class="kb-access-info">
|
||||
<span class="kb-access-role">
|
||||
<span class="kb-access-label">{{ $t('knowledgeBase.accessInfo.myRole') }}:</span>
|
||||
<t-tag size="small" :theme="isOwner ? 'success' : (currentSharedKb?.permission === 'admin' ? 'primary' : currentSharedKb?.permission === 'editor' ? 'warning' : 'default')">
|
||||
{{ accessRoleLabel }}
|
||||
</t-tag>
|
||||
</span>
|
||||
<span class="kb-access-summary">{{ accessPermissionSummary }}</span>
|
||||
<template v-if="currentSharedKb">
|
||||
<span class="kb-access-sep">·</span>
|
||||
<span class="kb-access-source">
|
||||
{{ $t('knowledgeBase.accessInfo.fromOrg') }}「{{ currentSharedKb.org_name }}」
|
||||
{{ $t('knowledgeBase.accessInfo.sharedAt') }} {{ formatStringDate(new Date(currentSharedKb.shared_at)) }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else-if="kbLastUpdated">
|
||||
<span class="kb-access-sep">·</span>
|
||||
<span class="kb-access-updated">{{ $t('knowledgeBase.accessInfo.lastUpdated') }} {{ kbLastUpdated }}</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="canEdit" class="document-header-actions">
|
||||
<t-dropdown
|
||||
:options="documentActionOptions"
|
||||
trigger="click"
|
||||
placement="bottom-right"
|
||||
@click="handleDocumentActionSelect"
|
||||
>
|
||||
<t-button class="doc-action-btn dropdown-action-btn">
|
||||
<template #icon><t-icon name="file-add" /></template>
|
||||
<span>{{ $t('knowledgeBase.addDocument') }}</span>
|
||||
<t-icon name="chevron-down" size="14px" class="dropdown-arrow" />
|
||||
</t-button>
|
||||
</t-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -962,6 +1195,13 @@ async function createNewSession(value: string): Promise<void> {
|
|||
multiple
|
||||
@change="handleDocumentUpload"
|
||||
/>
|
||||
<input
|
||||
ref="folderUploadInputRef"
|
||||
type="file"
|
||||
class="document-upload-input"
|
||||
webkitdirectory
|
||||
@change="handleFolderUpload"
|
||||
/>
|
||||
<div class="knowledge-main">
|
||||
<aside class="tag-sidebar">
|
||||
<div class="sidebar-header">
|
||||
|
|
@ -969,7 +1209,7 @@ async function createNewSession(value: string): Promise<void> {
|
|||
<span>{{ $t('knowledgeBase.documentCategoryTitle') }}</span>
|
||||
<span class="sidebar-count">({{ sidebarCategoryCount }})</span>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<div v-if="canEdit" class="sidebar-actions">
|
||||
<t-button
|
||||
size="small"
|
||||
variant="text"
|
||||
|
|
@ -1086,7 +1326,7 @@ async function createNewSession(value: string): Promise<void> {
|
|||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="tag-more" @click.stop>
|
||||
<div v-if="canEdit" class="tag-more" @click.stop>
|
||||
<t-popup trigger="click" placement="top-right" overlayClassName="tag-more-popup">
|
||||
<div class="tag-more-btn">
|
||||
<t-icon name="more" size="14px" />
|
||||
|
|
@ -1168,6 +1408,7 @@ async function createNewSession(value: string): Promise<void> {
|
|||
<div class="card-content-nav">
|
||||
<span class="card-content-title">{{ item.file_name }}</span>
|
||||
<t-popup
|
||||
v-if="canEdit"
|
||||
v-model="item.isMore"
|
||||
overlayClassName="card-more"
|
||||
:on-visible-change="onVisibleChange"
|
||||
|
|
@ -1232,6 +1473,7 @@ async function createNewSession(value: string): Promise<void> {
|
|||
<div class="card-bottom-right">
|
||||
<div v-if="tagList.length" class="card-tag-selector" @click.stop>
|
||||
<t-dropdown
|
||||
v-if="canEdit"
|
||||
:options="tagDropdownOptions"
|
||||
trigger="click"
|
||||
@click="(data: any) => handleKnowledgeTagChange(item.id, data.value as string)"
|
||||
|
|
@ -1240,6 +1482,9 @@ async function createNewSession(value: string): Promise<void> {
|
|||
<span class="tag-text">{{ getTagName(item.tag_id) }}</span>
|
||||
</t-tag>
|
||||
</t-dropdown>
|
||||
<t-tag v-else size="small" variant="light-outline">
|
||||
<span class="tag-text">{{ getTagName(item.tag_id) }}</span>
|
||||
</t-tag>
|
||||
</div>
|
||||
<div class="card-type">
|
||||
<span>{{ getKnowledgeType(item) }}</span>
|
||||
|
|
@ -1869,6 +2114,34 @@ async function createNewSession(value: string): Promise<void> {
|
|||
gap: 4px;
|
||||
}
|
||||
|
||||
.document-header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.doc-action-btn {
|
||||
background: linear-gradient(135deg, #07c05f 0%, #00a67e 100%);
|
||||
border: none;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, #05a04f 0%, #008a6a 100%);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.dropdown-action-btn) {
|
||||
.t-button__text {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.dropdown-arrow {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.document-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
|
@ -1954,8 +2227,43 @@ async function createNewSession(value: string): Promise<void> {
|
|||
line-height: 20px;
|
||||
}
|
||||
|
||||
.kb-access-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 12px;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #86909c;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.kb-access-label {
|
||||
color: #4e5969;
|
||||
}
|
||||
|
||||
.kb-access-role {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.kb-access-summary {
|
||||
color: #86909c;
|
||||
}
|
||||
|
||||
.kb-access-sep {
|
||||
color: #c9ced6;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.kb-access-source,
|
||||
.kb-access-updated {
|
||||
color: #86909c;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
.document-upload-input {
|
||||
display: none;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,6 +150,11 @@
|
|||
@update:question-generation="handleQuestionGenerationUpdate"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 共享设置(仅编辑模式) -->
|
||||
<div v-if="mode === 'edit' && kbId" v-show="currentSection === 'share'" class="section">
|
||||
<KBShareSettings :kb-id="kbId" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 保存按钮 -->
|
||||
|
|
@ -180,6 +185,7 @@ import KBModelConfig from './settings/KBModelConfig.vue'
|
|||
import KBChunkingSettings from './settings/KBChunkingSettings.vue'
|
||||
import KBAdvancedSettings from './settings/KBAdvancedSettings.vue'
|
||||
import GraphSettings from './settings/GraphSettings.vue'
|
||||
import KBShareSettings from './settings/KBShareSettings.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const uiStore = useUIStore()
|
||||
|
|
@ -219,6 +225,10 @@ const navItems = computed(() => {
|
|||
{ key: 'advanced', icon: 'setting', label: t('knowledgeEditor.sidebar.advanced') }
|
||||
)
|
||||
}
|
||||
// 只在编辑模式下显示共享标签页
|
||||
if (props.mode === 'edit' && props.kbId) {
|
||||
items.push({ key: 'share', icon: 'share', label: t('knowledgeEditor.sidebar.share') })
|
||||
}
|
||||
return items
|
||||
})
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -39,11 +39,10 @@
|
|||
<t-icon name="chevron-right" class="breadcrumb-separator" />
|
||||
<span class="breadcrumb-current">{{ $t('knowledgeEditor.faq.title') }}</span>
|
||||
</h2>
|
||||
<t-tooltip :content="$t('knowledgeBase.settings')" placement="top">
|
||||
<t-tooltip v-if="canManage" :content="$t('knowledgeBase.settings')" placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="kb-settings-button"
|
||||
:disabled="!props.kbId"
|
||||
@click="handleOpenKBSettings"
|
||||
>
|
||||
<t-icon name="setting" size="16px" />
|
||||
|
|
@ -51,6 +50,41 @@
|
|||
</t-tooltip>
|
||||
</div>
|
||||
<p class="faq-subtitle">{{ $t('knowledgeEditor.faq.subtitle') }}</p>
|
||||
<!-- 当前知识库权限与来源信息 -->
|
||||
<div v-if="kbInfo" class="faq-access-info">
|
||||
<span class="faq-access-role">
|
||||
<span class="faq-access-label">{{ $t('knowledgeBase.accessInfo.myRole') }}:</span>
|
||||
<t-tag size="small" :theme="isOwner ? 'success' : (currentSharedKb?.permission === 'admin' ? 'primary' : currentSharedKb?.permission === 'editor' ? 'warning' : 'default')">
|
||||
{{ accessRoleLabel }}
|
||||
</t-tag>
|
||||
</span>
|
||||
<span class="faq-access-summary">{{ accessPermissionSummary }}</span>
|
||||
<template v-if="currentSharedKb">
|
||||
<span class="faq-access-sep">·</span>
|
||||
<span class="faq-access-source">
|
||||
{{ $t('knowledgeBase.accessInfo.fromOrg') }}「{{ currentSharedKb.org_name }}」
|
||||
{{ $t('knowledgeBase.accessInfo.sharedAt') }} {{ formatImportTime(currentSharedKb.shared_at) }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else-if="kbLastUpdated">
|
||||
<span class="faq-access-sep">·</span>
|
||||
<span class="faq-access-updated">{{ $t('knowledgeBase.accessInfo.lastUpdated') }} {{ kbLastUpdated }}</span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="faq-header-actions">
|
||||
<t-dropdown
|
||||
:options="faqActionOptions"
|
||||
trigger="click"
|
||||
placement="bottom-right"
|
||||
@click="handleFaqAction"
|
||||
>
|
||||
<t-button class="faq-action-btn dropdown-action-btn">
|
||||
<template #icon><t-icon name="help-circle" /></template>
|
||||
<span>{{ $t('knowledgeEditor.faq.manageFaq') }}</span>
|
||||
<t-icon name="chevron-down" size="14px" class="dropdown-arrow" />
|
||||
</t-button>
|
||||
</t-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -173,7 +207,7 @@
|
|||
<span>{{ $t('knowledgeBase.faqCategoryTitle') }}</span>
|
||||
<span class="sidebar-count">({{ sidebarCategoryCount }})</span>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<div v-if="canEdit" class="sidebar-actions">
|
||||
<t-button
|
||||
size="small"
|
||||
variant="text"
|
||||
|
|
@ -290,7 +324,7 @@
|
|||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="tag-more" @click.stop>
|
||||
<div v-if="canEdit" class="tag-more" @click.stop>
|
||||
<t-popup trigger="click" placement="top-right" overlayClassName="tag-more-popup">
|
||||
<div class="tag-more-btn">
|
||||
<t-icon name="more" size="14px" />
|
||||
|
|
@ -359,6 +393,7 @@
|
|||
</div>
|
||||
<div class="faq-card-actions">
|
||||
<t-popup
|
||||
v-if="canManage"
|
||||
v-model="entry.showMore"
|
||||
overlayClassName="faq-card-popup"
|
||||
trigger="click"
|
||||
|
|
@ -502,7 +537,7 @@
|
|||
<!-- Card Footer -->
|
||||
<div class="faq-card-footer">
|
||||
<div class="faq-card-tag" @click.stop>
|
||||
<template v-if="tagList.length">
|
||||
<template v-if="canEdit && tagList.length">
|
||||
<t-dropdown
|
||||
:options="tagDropdownOptions"
|
||||
trigger="click"
|
||||
|
|
@ -539,22 +574,21 @@
|
|||
</div>
|
||||
</t-tooltip>
|
||||
-->
|
||||
<t-tooltip
|
||||
:content="entry.is_enabled ? $t('knowledgeEditor.faq.statusEnabled') : $t('knowledgeEditor.faq.statusDisabled')"
|
||||
placement="top"
|
||||
>
|
||||
<div class="status-item-compact">
|
||||
<t-switch
|
||||
:key="`${entry.id}-${entry.is_enabled}`"
|
||||
size="small"
|
||||
:value="entry.is_enabled"
|
||||
:loading="!!entryStatusLoading[entry.id]"
|
||||
:disabled="!!entryStatusLoading[entry.id]"
|
||||
@click.stop
|
||||
@change="(value: boolean) => handleEntryStatusChange(entry, value)"
|
||||
/>
|
||||
</div>
|
||||
</t-tooltip>
|
||||
<t-tooltip
|
||||
:content="entry.is_enabled ? $t('knowledgeEditor.faq.statusEnabled') : $t('knowledgeEditor.faq.statusDisabled')"
|
||||
placement="top"
|
||||
>
|
||||
<div class="status-item-compact">
|
||||
<t-switch
|
||||
:key="`${entry.id}-${entry.is_enabled}`"
|
||||
size="small"
|
||||
:value="entry.is_enabled"
|
||||
:loading="!!entryStatusLoading[entry.id]"
|
||||
:disabled="!!entryStatusLoading[entry.id] || !canEdit"
|
||||
@click.stop @change="(value: boolean) => handleEntryStatusChange(entry, value)"
|
||||
/>
|
||||
</div>
|
||||
</t-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -1161,6 +1195,8 @@ import { MessagePlugin, DialogPlugin, Icon as TIcon } from 'tdesign-vue-next'
|
|||
import type { FormRules, FormInstanceFunctions } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import {
|
||||
listFAQEntries,
|
||||
upsertFAQEntries,
|
||||
|
|
@ -1226,6 +1262,95 @@ const props = defineProps<{
|
|||
const { t } = useI18n()
|
||||
const router = useRouter()
|
||||
const uiStore = useUIStore()
|
||||
const authStore = useAuthStore()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
// Permission control: check if current user owns this KB or has edit/manage permission
|
||||
const isOwner = computed(() => {
|
||||
if (!kbInfo.value) return false
|
||||
// Check if the current user's tenant ID matches the KB's tenant ID
|
||||
const userTenantId = authStore.effectiveTenantId
|
||||
return kbInfo.value.tenant_id === userTenantId
|
||||
})
|
||||
|
||||
// Can edit: owner, admin, or editor
|
||||
const canEdit = computed(() => {
|
||||
return orgStore.canEditKB(props.kbId, isOwner.value)
|
||||
})
|
||||
|
||||
// Can manage (delete, settings, etc.): owner or admin
|
||||
const canManage = computed(() => {
|
||||
return orgStore.canManageKB(props.kbId, isOwner.value)
|
||||
})
|
||||
|
||||
// Current KB's shared record (when accessed via organization share)
|
||||
const currentSharedKb = computed(() =>
|
||||
orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === props.kbId) ?? null,
|
||||
)
|
||||
|
||||
// Display role label: owner or org role (admin/editor/viewer)
|
||||
const accessRoleLabel = computed(() => {
|
||||
if (isOwner.value) return t('knowledgeBase.accessInfo.roleOwner')
|
||||
const perm = orgStore.getKBPermission(props.kbId)
|
||||
if (perm) return t(`organization.role.${perm}`)
|
||||
return '--'
|
||||
})
|
||||
|
||||
// Permission summary text for current role
|
||||
const accessPermissionSummary = computed(() => {
|
||||
if (isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner')
|
||||
const perm = orgStore.getKBPermission(props.kbId)
|
||||
if (perm === 'admin') return t('knowledgeBase.accessInfo.permissionAdmin')
|
||||
if (perm === 'editor') return t('knowledgeBase.accessInfo.permissionEditor')
|
||||
if (perm === 'viewer') return t('knowledgeBase.accessInfo.permissionViewer')
|
||||
return '--'
|
||||
})
|
||||
|
||||
// Last updated time from kbInfo
|
||||
const kbLastUpdated = computed(() => {
|
||||
const raw = kbInfo.value?.updated_at
|
||||
if (!raw) return null
|
||||
return formatImportTime(raw)
|
||||
})
|
||||
|
||||
// FAQ 操作下拉选项
|
||||
const faqActionOptions = computed(() => {
|
||||
const options = []
|
||||
|
||||
// 编辑权限相关操作
|
||||
if (canEdit.value) {
|
||||
options.push(
|
||||
{ content: t('knowledgeEditor.faq.editorCreate'), value: 'create', prefixIcon: () => h(TIcon, { name: 'add', size: '16px' }) },
|
||||
{ content: t('knowledgeEditor.faqImport.importButton'), value: 'import', prefixIcon: () => h(TIcon, { name: 'upload', size: '16px' }) },
|
||||
)
|
||||
}
|
||||
|
||||
// 通用操作
|
||||
options.push(
|
||||
{ content: t('knowledgeEditor.faq.searchTest'), value: 'search', prefixIcon: () => h(TIcon, { name: 'search', size: '16px' }) },
|
||||
{ content: t('knowledgeEditor.faqExport.exportButton'), value: 'export', prefixIcon: () => h(TIcon, { name: 'download', size: '16px' }) },
|
||||
)
|
||||
|
||||
return options
|
||||
})
|
||||
|
||||
// 处理 FAQ 操作
|
||||
const handleFaqAction = (data: { value: string }) => {
|
||||
switch (data.value) {
|
||||
case 'create':
|
||||
openEditor()
|
||||
break
|
||||
case 'import':
|
||||
openImportDialog()
|
||||
break
|
||||
case 'search':
|
||||
searchDrawerVisible.value = true
|
||||
break
|
||||
case 'export':
|
||||
handleExportCSV()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const loadingMore = ref(false)
|
||||
|
|
@ -1336,11 +1461,26 @@ const loadKnowledgeInfo = async (kbId: string) => {
|
|||
const loadKnowledgeList = async () => {
|
||||
try {
|
||||
const res: any = await listKnowledgeBases()
|
||||
knowledgeList.value = (res?.data || []).map((item: any) => ({
|
||||
const myKbs = (res?.data || []).map((item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
}))
|
||||
|
||||
// Also include shared knowledge bases from orgStore
|
||||
const sharedKbs = (orgStore.sharedKnowledgeBases || [])
|
||||
.filter(s => s.knowledge_base != null)
|
||||
.map(s => ({
|
||||
id: String(s.knowledge_base.id),
|
||||
name: s.knowledge_base.name,
|
||||
type: s.knowledge_base.type,
|
||||
}))
|
||||
|
||||
// Merge and deduplicate by id (my KBs take precedence)
|
||||
const myKbIds = new Set(myKbs.map(kb => kb.id))
|
||||
const uniqueSharedKbs = sharedKbs.filter(kb => !myKbIds.has(kb.id))
|
||||
|
||||
knowledgeList.value = [...myKbs, ...uniqueSharedKbs]
|
||||
} catch (error) {
|
||||
console.error('Failed to load knowledge bases:', error)
|
||||
}
|
||||
|
|
@ -1671,13 +1811,15 @@ const handleKnowledgeDropdownSelect = (data: { value: string }) => {
|
|||
const handleFaqMenuAction = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ action: string; kbId: string }>).detail
|
||||
if (!detail || detail.kbId !== props.kbId) return
|
||||
|
||||
if (detail.action === 'create') {
|
||||
openEditor()
|
||||
if (canEdit.value) openEditor()
|
||||
} else if (detail.action === 'import') {
|
||||
openImportDialog()
|
||||
if (canEdit.value) openImportDialog()
|
||||
} else if (detail.action === 'search') {
|
||||
searchDrawerVisible.value = true
|
||||
} else if (detail.action === 'export') {
|
||||
// Export is usually allowed for viewers as well
|
||||
handleExportCSV()
|
||||
} else if (detail.action === 'batch') {
|
||||
// 批量操作通过左侧菜单的下拉菜单处理
|
||||
|
|
@ -1685,19 +1827,19 @@ const handleFaqMenuAction = (event: Event) => {
|
|||
MessagePlugin.warning(t('knowledgeEditor.faq.selectEntriesFirst') || '请先选中要操作的FAQ条目')
|
||||
}
|
||||
} else if (detail.action === 'batchTag') {
|
||||
if (selectedRowKeys.value.length > 0) {
|
||||
if (canEdit.value && selectedRowKeys.value.length > 0) {
|
||||
openBatchTagDialog()
|
||||
}
|
||||
} else if (detail.action === 'batchEnable') {
|
||||
if (selectedRowKeys.value.length > 0) {
|
||||
if (canEdit.value && selectedRowKeys.value.length > 0) {
|
||||
handleBatchStatusChange(true)
|
||||
}
|
||||
} else if (detail.action === 'batchDisable') {
|
||||
if (selectedRowKeys.value.length > 0) {
|
||||
if (canEdit.value && selectedRowKeys.value.length > 0) {
|
||||
handleBatchStatusChange(false)
|
||||
}
|
||||
} else if (detail.action === 'batchDelete') {
|
||||
if (selectedRowKeys.value.length > 0) {
|
||||
if (canManage.value && selectedRowKeys.value.length > 0) {
|
||||
handleBatchDelete()
|
||||
}
|
||||
}
|
||||
|
|
@ -3021,6 +3163,8 @@ const handleResize = () => {
|
|||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// Ensure shared knowledge bases are loaded before loading the knowledge list
|
||||
orgStore.fetchSharedKnowledgeBases()
|
||||
loadKnowledgeList()
|
||||
window.addEventListener('resize', handleResize)
|
||||
window.addEventListener('faqMenuAction', handleFaqMenuAction as EventListener)
|
||||
|
|
@ -3603,6 +3747,160 @@ watch(() => entries.value.map(e => ({
|
|||
margin-bottom: 20px;
|
||||
border-bottom: 1px solid #e7ebf0;
|
||||
flex-shrink: 0;
|
||||
|
||||
.faq-header-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.faq-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.faq-breadcrumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #1d2129;
|
||||
}
|
||||
|
||||
.breadcrumb-link {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px 8px;
|
||||
margin: -4px -8px;
|
||||
font: inherit;
|
||||
color: #4e5969;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.12s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: #10b981;
|
||||
background: #f6f8f7;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
color: #c9ced6;
|
||||
}
|
||||
|
||||
&.dropdown {
|
||||
padding-right: 6px;
|
||||
|
||||
:deep(.t-icon) {
|
||||
font-size: 14px;
|
||||
transition: transform 0.12s ease;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
:deep(.t-icon) {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.breadcrumb-separator {
|
||||
font-size: 14px;
|
||||
color: #c9ced6;
|
||||
}
|
||||
|
||||
.breadcrumb-current {
|
||||
color: #1d2129;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
color: #1d2129;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
line-height: 32px;
|
||||
}
|
||||
|
||||
.faq-subtitle {
|
||||
margin: 0;
|
||||
color: #00000099;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.faq-access-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 12px;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #86909c;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.faq-access-label {
|
||||
color: #4e5969;
|
||||
}
|
||||
|
||||
.faq-access-role {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.faq-access-summary {
|
||||
color: #86909c;
|
||||
}
|
||||
|
||||
.faq-access-sep {
|
||||
color: #c9ced6;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.faq-access-source,
|
||||
.faq-access-updated {
|
||||
color: #86909c;
|
||||
}
|
||||
}
|
||||
|
||||
.faq-header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.faq-action-btn {
|
||||
background: linear-gradient(135deg, #26a69a 0%, #00897b 100%);
|
||||
border: none;
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, #00897b 0%, #00796b 100%);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.dropdown-action-btn) {
|
||||
.t-button__text {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.dropdown-arrow {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 导入进度条样式(显示在列表页面顶部)
|
||||
|
|
@ -3850,97 +4148,6 @@ watch(() => entries.value.map(e => ({
|
|||
}
|
||||
}
|
||||
|
||||
.faq-header-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.faq-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.faq-breadcrumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #1d2129;
|
||||
}
|
||||
|
||||
.breadcrumb-link {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px 8px;
|
||||
margin: -4px -8px;
|
||||
font: inherit;
|
||||
color: #4e5969;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.12s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: #10b981;
|
||||
background: #f6f8f7;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
color: #c9ced6;
|
||||
}
|
||||
|
||||
&.dropdown {
|
||||
padding-right: 6px;
|
||||
|
||||
:deep(.t-icon) {
|
||||
font-size: 14px;
|
||||
transition: transform 0.12s ease;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
:deep(.t-icon) {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.breadcrumb-separator {
|
||||
font-size: 14px;
|
||||
color: #c9ced6;
|
||||
}
|
||||
|
||||
.breadcrumb-current {
|
||||
color: #1d2129;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
color: #1d2129;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
line-height: 32px;
|
||||
}
|
||||
|
||||
.faq-subtitle {
|
||||
margin: 0;
|
||||
color: #00000099;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
|
||||
.tag-filter-bar {
|
||||
display: flex;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,550 @@
|
|||
<template>
|
||||
<div class="section-content">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{{ $t('organization.share.title') }}</h3>
|
||||
<p class="section-desc">{{ $t('knowledgeEditor.share.description') }}</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<!-- 共享表单 -->
|
||||
<div class="share-form">
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ $t('organization.share.selectOrg') }}</label>
|
||||
<div class="share-input-row">
|
||||
<t-select
|
||||
v-model="selectedOrgId"
|
||||
:placeholder="$t('organization.share.selectOrgPlaceholder')"
|
||||
:loading="loadingOrgs"
|
||||
class="org-select"
|
||||
>
|
||||
<t-option
|
||||
v-for="org in availableOrganizations"
|
||||
:key="org.id"
|
||||
:value="org.id"
|
||||
:label="org.name"
|
||||
>
|
||||
<div class="org-option-content">
|
||||
<div class="org-option-header">
|
||||
<span class="org-option-name">{{ org.name }}</span>
|
||||
<t-tag v-if="org.is_owner" theme="primary" size="small" variant="light">
|
||||
{{ $t('organization.owner') }}
|
||||
</t-tag>
|
||||
<t-tag v-else-if="org.my_role" :theme="org.my_role === 'admin' ? 'warning' : 'default'" size="small" variant="light">
|
||||
{{ $t(`organization.role.${org.my_role}`) }}
|
||||
</t-tag>
|
||||
</div>
|
||||
<div v-if="org.description" class="org-option-desc">{{ org.description }}</div>
|
||||
<div class="org-option-meta">
|
||||
<span class="org-meta-item">
|
||||
<t-icon name="usergroup" size="14px" />
|
||||
{{ org.member_count || 0 }} {{ $t('organization.members') }}
|
||||
</span>
|
||||
<span v-if="org.share_count !== undefined" class="org-meta-item">
|
||||
<t-icon name="share" size="14px" />
|
||||
{{ org.share_count }} {{ $t('organization.share.sharedKBs') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</t-option>
|
||||
</t-select>
|
||||
<t-select
|
||||
v-model="selectedPermission"
|
||||
class="permission-select"
|
||||
>
|
||||
<t-option value="viewer" :label="$t('organization.share.permissionReadonly')" />
|
||||
<t-option value="editor" :label="$t('organization.share.permissionEditable')" />
|
||||
</t-select>
|
||||
<t-button
|
||||
theme="primary"
|
||||
:loading="submitting"
|
||||
:disabled="!selectedOrgId"
|
||||
@click="handleShare"
|
||||
>
|
||||
{{ $t('knowledgeEditor.share.addShare') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="form-tip">{{ $t('organization.share.permissionTip') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 已共享列表 -->
|
||||
<div class="shares-section">
|
||||
<div class="shares-header">
|
||||
<span class="shares-title">{{ $t('organization.share.sharedTo') }}</span>
|
||||
<span class="shares-count">{{ shares.length }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="loadingShares" class="shares-loading">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('common.loading') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else-if="shares.length === 0" class="shares-empty">
|
||||
<t-icon name="share" class="empty-icon" />
|
||||
<span>{{ $t('organization.share.noShares') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-else class="shares-list">
|
||||
<div v-for="share in shares" :key="share.id" class="share-item">
|
||||
<div class="share-info">
|
||||
<div class="share-org">
|
||||
<t-icon name="usergroup" class="org-icon" />
|
||||
<span class="org-name">{{ share.organization_name }}</span>
|
||||
</div>
|
||||
<t-tag
|
||||
:theme="share.permission === 'editor' ? 'warning' : 'default'"
|
||||
size="small"
|
||||
variant="light"
|
||||
>
|
||||
{{ share.permission === 'editor' ? $t('organization.share.permissionEditable') : $t('organization.share.permissionReadonly') }}
|
||||
</t-tag>
|
||||
</div>
|
||||
<div class="share-actions">
|
||||
<t-select
|
||||
:value="share.permission"
|
||||
size="small"
|
||||
class="permission-change-select"
|
||||
@change="(val: string) => handleUpdatePermission(share, val)"
|
||||
>
|
||||
<t-option value="viewer" :label="$t('organization.share.permissionReadonly')" />
|
||||
<t-option value="editor" :label="$t('organization.share.permissionEditable')" />
|
||||
</t-select>
|
||||
<t-popconfirm
|
||||
:content="$t('knowledgeEditor.share.unshareConfirm', { name: share.organization_name })"
|
||||
@confirm="handleUnshare(share)"
|
||||
>
|
||||
<t-button variant="text" theme="danger" size="small">
|
||||
<t-icon name="delete" />
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 提示信息 -->
|
||||
<div class="share-tips">
|
||||
<t-icon name="info-circle" class="tip-icon" />
|
||||
<div class="tip-content">
|
||||
<p>{{ $t('knowledgeEditor.share.tip1') }}</p>
|
||||
<p>{{ $t('knowledgeEditor.share.tip2') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { shareKnowledgeBase, listKBShares, removeShare, updateSharePermission } from '@/api/organization'
|
||||
import type { KnowledgeBaseShare } from '@/api/organization'
|
||||
|
||||
const { t } = useI18n()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
interface Props {
|
||||
kbId: string
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const loadingOrgs = ref(false)
|
||||
const loadingShares = ref(false)
|
||||
const submitting = ref(false)
|
||||
const selectedOrgId = ref('')
|
||||
const selectedPermission = ref<'viewer' | 'editor'>('viewer')
|
||||
const shares = ref<(KnowledgeBaseShare & { organization_name?: string })[]>([])
|
||||
|
||||
// Only show organizations where user can share (editor or admin); exclude viewer-only orgs and already shared
|
||||
const availableOrganizations = computed(() => {
|
||||
const sharedOrgIds = new Set(shares.value.map(s => s.organization_id))
|
||||
return orgStore.organizations.filter(
|
||||
(org) =>
|
||||
!sharedOrgIds.has(org.id) &&
|
||||
(org.is_owner === true || org.my_role === 'admin' || org.my_role === 'editor')
|
||||
)
|
||||
})
|
||||
|
||||
// Load organizations
|
||||
async function loadOrganizations() {
|
||||
loadingOrgs.value = true
|
||||
try {
|
||||
await orgStore.fetchOrganizations()
|
||||
} finally {
|
||||
loadingOrgs.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Load shares
|
||||
async function loadShares() {
|
||||
if (!props.kbId) return
|
||||
loadingShares.value = true
|
||||
try {
|
||||
const result = await listKBShares(props.kbId)
|
||||
if (result.success && result.data) {
|
||||
// result.data is ListSharesResponse with shares array
|
||||
const sharesData = (result.data as any).shares || result.data
|
||||
const sharesList = Array.isArray(sharesData) ? sharesData : []
|
||||
shares.value = sharesList.map((share: KnowledgeBaseShare) => ({
|
||||
...share,
|
||||
organization_name: share.organization_name || orgStore.organizations.find(o => o.id === share.organization_id)?.name || share.organization_id
|
||||
}))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load shares:', e)
|
||||
} finally {
|
||||
loadingShares.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Handle share
|
||||
async function handleShare() {
|
||||
if (!selectedOrgId.value) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await shareKnowledgeBase(props.kbId, {
|
||||
organization_id: selectedOrgId.value,
|
||||
permission: selectedPermission.value
|
||||
})
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.shareSuccess'))
|
||||
selectedOrgId.value = ''
|
||||
selectedPermission.value = 'viewer'
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.shareFailed'))
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('organization.share.shareFailed'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Handle update permission
|
||||
async function handleUpdatePermission(share: KnowledgeBaseShare, newPermission: string) {
|
||||
if (share.permission === newPermission) return
|
||||
|
||||
try {
|
||||
const result = await updateSharePermission(props.kbId, share.id, {
|
||||
permission: newPermission as 'viewer' | 'editor'
|
||||
})
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.roleUpdated'))
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.roleUpdateFailed'))
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('organization.roleUpdateFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
// Handle unshare
|
||||
async function handleUnshare(share: KnowledgeBaseShare) {
|
||||
try {
|
||||
const result = await removeShare(props.kbId, share.id)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.unshareSuccess'))
|
||||
await loadShares()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.share.unshareFailed'))
|
||||
}
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('organization.share.unshareFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
// Watch for kbId changes
|
||||
watch(() => props.kbId, async (newKbId) => {
|
||||
if (newKbId) {
|
||||
await Promise.all([loadOrganizations(), loadShares()])
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
onMounted(async () => {
|
||||
if (props.kbId) {
|
||||
await Promise.all([loadOrganizations(), loadShares()])
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.section-content {
|
||||
.section-header {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 0 0 8px 0;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.section-desc {
|
||||
margin: 0;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
color: #00000066;
|
||||
line-height: 22px;
|
||||
}
|
||||
}
|
||||
|
||||
.share-form {
|
||||
margin-bottom: 24px;
|
||||
padding-bottom: 24px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.form-item {
|
||||
.form-label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.form-tip {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
line-height: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.share-input-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
|
||||
.org-select {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.permission-select {
|
||||
width: 120px;
|
||||
}
|
||||
}
|
||||
|
||||
.shares-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.shares-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
|
||||
.shares-title {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.shares-count {
|
||||
padding: 2px 8px;
|
||||
background: #f5f5f5;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
}
|
||||
}
|
||||
|
||||
.shares-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 32px;
|
||||
color: #00000066;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.shares-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 40px 20px;
|
||||
background: #fafafa;
|
||||
border-radius: 8px;
|
||||
color: #00000066;
|
||||
|
||||
.empty-icon {
|
||||
font-size: 32px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.shares-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.share-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
background: #fafafa;
|
||||
border-radius: 8px;
|
||||
transition: background 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: #f5f5f5;
|
||||
}
|
||||
}
|
||||
|
||||
.share-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.share-org {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.org-icon {
|
||||
font-size: 16px;
|
||||
color: #0052d9;
|
||||
}
|
||||
|
||||
.org-name {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
}
|
||||
|
||||
.share-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.permission-change-select {
|
||||
width: 100px;
|
||||
}
|
||||
}
|
||||
|
||||
.share-tips {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
background: #f0f7ff;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e6f0ff;
|
||||
|
||||
.tip-icon {
|
||||
flex-shrink: 0;
|
||||
font-size: 16px;
|
||||
color: #0052d9;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.tip-content {
|
||||
flex: 1;
|
||||
|
||||
p {
|
||||
margin: 0 0 4px 0;
|
||||
font-size: 13px;
|
||||
color: #00000099;
|
||||
line-height: 20px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Custom option styles for organization select
|
||||
:deep(.t-select-option) {
|
||||
height: auto;
|
||||
align-items: flex-start;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
:deep(.t-select-option__content) {
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.org-option-content {
|
||||
padding: 2px 0;
|
||||
min-width: 280px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.org-option-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
|
||||
.org-option-name {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
}
|
||||
|
||||
.org-option-desc {
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
line-height: 18px;
|
||||
margin-bottom: 6px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.org-option-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
|
||||
.org-meta-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
// Global styles for select dropdown (outside scoped)
|
||||
.t-select__dropdown .t-select-option {
|
||||
height: auto;
|
||||
align-items: flex-start;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.t-select__dropdown .t-select-option__content {
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
<template>
|
||||
<div class="join-page">
|
||||
<div class="join-card">
|
||||
<div class="join-icon">
|
||||
<t-icon name="user-add" size="48px" />
|
||||
</div>
|
||||
<h2 class="join-title">{{ $t('organization.join.title') }}</h2>
|
||||
<p v-if="loading" class="join-message">{{ $t('organization.join.joining') }}</p>
|
||||
<p v-else-if="error" class="join-message error">{{ error }}</p>
|
||||
<p v-else class="join-message success">{{ $t('organization.join.success') }}</p>
|
||||
|
||||
<t-button
|
||||
v-if="!loading"
|
||||
theme="primary"
|
||||
@click="goToOrganizations"
|
||||
>
|
||||
{{ $t('organization.join.goToOrganizations') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
|
||||
onMounted(async () => {
|
||||
const code = route.query.code as string
|
||||
|
||||
if (!code) {
|
||||
error.value = t('organization.join.noCode')
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await orgStore.join(code)
|
||||
if (result) {
|
||||
MessagePlugin.success(t('organization.join.success'))
|
||||
} else {
|
||||
error.value = orgStore.error || t('organization.join.failed')
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || t('organization.join.failed')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
const goToOrganizations = () => {
|
||||
router.push('/platform/organizations')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.join-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #f7f9fc 0%, #e6f7ec 100%);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.join-card {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
padding: 48px;
|
||||
text-align: center;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.join-icon {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
margin: 0 auto 24px;
|
||||
border-radius: 50%;
|
||||
background: #e6f7ec;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #00a870;
|
||||
}
|
||||
|
||||
.join-title {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #1d2129;
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
|
||||
.join-message {
|
||||
font-size: 14px;
|
||||
color: #86909c;
|
||||
margin: 0 0 24px;
|
||||
|
||||
&.error {
|
||||
color: #e34d59;
|
||||
}
|
||||
|
||||
&.success {
|
||||
color: #00a870;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,900 @@
|
|||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="modal">
|
||||
<div v-if="visible" class="settings-overlay" @click.self="handleClose">
|
||||
<div class="settings-modal" :class="{ 'join-mode': mode === 'join' }">
|
||||
<!-- 关闭按钮 -->
|
||||
<button class="close-btn" @click="handleClose" :aria-label="$t('common.close')">
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div class="settings-container">
|
||||
<!-- 左侧导航 -->
|
||||
<div class="settings-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h2 class="sidebar-title">{{ modalTitle }}</h2>
|
||||
</div>
|
||||
<div class="settings-nav">
|
||||
<div
|
||||
v-for="(item, index) in navItems"
|
||||
:key="index"
|
||||
:class="['nav-item', { 'active': currentSection === item.key }]"
|
||||
@click="currentSection = item.key"
|
||||
>
|
||||
<t-icon :name="item.icon" class="nav-icon" />
|
||||
<span class="nav-label">{{ item.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧内容区域 -->
|
||||
<div class="settings-content">
|
||||
<div class="content-wrapper">
|
||||
<!-- 创建组织 - 基本信息 -->
|
||||
<div v-if="mode === 'create'" v-show="currentSection === 'basic'" class="section">
|
||||
<div class="section-content">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{{ $t('organization.editor.basicTitle') }}</h3>
|
||||
<p class="section-desc">{{ $t('organization.editor.basicDesc') }}</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="form-item">
|
||||
<label class="form-label required">{{ $t('organization.name') }}</label>
|
||||
<div class="name-input-wrapper">
|
||||
<SpaceAvatar :name="createForm.name || '?'" size="large" />
|
||||
<t-input
|
||||
v-model="createForm.name"
|
||||
:placeholder="$t('organization.namePlaceholder')"
|
||||
:maxlength="100"
|
||||
class="name-input"
|
||||
/>
|
||||
</div>
|
||||
<p class="form-tip">{{ $t('organization.editor.nameTip') }}</p>
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ $t('organization.description') }}</label>
|
||||
<t-textarea
|
||||
v-model="createForm.description"
|
||||
:placeholder="$t('organization.descriptionPlaceholder')"
|
||||
:maxlength="500"
|
||||
:autosize="{ minRows: 3, maxRows: 6 }"
|
||||
/>
|
||||
<p class="form-tip">{{ $t('organization.editor.descriptionTip') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 创建组织 - 权限说明 -->
|
||||
<div v-if="mode === 'create'" v-show="currentSection === 'permissions'" class="section">
|
||||
<div class="section-content">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{{ $t('organization.editor.permissionsTitle') }}</h3>
|
||||
<p class="section-desc">{{ $t('organization.editor.permissionsDesc') }}</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="permissions-info">
|
||||
<div class="permission-card">
|
||||
<div class="permission-header">
|
||||
<div class="permission-icon admin">
|
||||
<t-icon name="user-safety" />
|
||||
</div>
|
||||
<div class="permission-title">
|
||||
<span class="role-name">{{ $t('organization.role.admin') }}</span>
|
||||
<t-tag size="small" theme="primary">{{ $t('organization.editor.fullAccess') }}</t-tag>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="permission-list">
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.adminPerm1') }}</li>
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.adminPerm2') }}</li>
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.adminPerm3') }}</li>
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.adminPerm4') }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="permission-card">
|
||||
<div class="permission-header">
|
||||
<div class="permission-icon editor">
|
||||
<t-icon name="edit" />
|
||||
</div>
|
||||
<div class="permission-title">
|
||||
<span class="role-name">{{ $t('organization.role.editor') }}</span>
|
||||
<t-tag size="small" theme="warning">{{ $t('organization.editor.editAccess') }}</t-tag>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="permission-list">
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.editorPerm1') }}</li>
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.editorPerm2') }}</li>
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.shareKBPerm') }}</li>
|
||||
<li><t-icon name="close" class="close-icon" />{{ $t('organization.editor.editorPerm3') }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="permission-card">
|
||||
<div class="permission-header">
|
||||
<div class="permission-icon viewer">
|
||||
<t-icon name="browse" />
|
||||
</div>
|
||||
<div class="permission-title">
|
||||
<span class="role-name">{{ $t('organization.role.viewer') }}</span>
|
||||
<t-tag size="small">{{ $t('organization.editor.viewAccess') }}</t-tag>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="permission-list">
|
||||
<li><t-icon name="check" class="check-icon" />{{ $t('organization.editor.viewerPerm1') }}</li>
|
||||
<li><t-icon name="close" class="close-icon" />{{ $t('organization.editor.shareKBPerm') }}</li>
|
||||
<li><t-icon name="close" class="close-icon" />{{ $t('organization.editor.viewerPerm2') }}</li>
|
||||
<li><t-icon name="close" class="close-icon" />{{ $t('organization.editor.viewerPerm3') }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-notice">
|
||||
<t-icon name="info-circle" />
|
||||
<span>{{ $t('organization.editor.ownerNote') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加入组织 -->
|
||||
<div v-if="mode === 'join'" v-show="currentSection === 'join'" class="section">
|
||||
<div class="section-content">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">{{ $t('organization.editor.joinTitle') }}</h3>
|
||||
<p class="section-desc">{{ $t('organization.editor.joinDesc') }}</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="join-illustration">
|
||||
<div class="illustration-icon">
|
||||
<t-icon name="user-add" size="48px" />
|
||||
</div>
|
||||
<p class="illustration-text">{{ $t('organization.editor.joinIllustration') }}</p>
|
||||
</div>
|
||||
<div class="form-item">
|
||||
<label class="form-label required">{{ $t('organization.inviteCode') }}</label>
|
||||
<t-input
|
||||
v-model="joinForm.invite_code"
|
||||
:placeholder="$t('organization.inviteCodePlaceholder')"
|
||||
:maxlength="32"
|
||||
size="large"
|
||||
class="invite-code-input"
|
||||
/>
|
||||
<p class="form-tip">{{ $t('organization.editor.inviteCodeTip') }}</p>
|
||||
</div>
|
||||
<div class="join-steps">
|
||||
<div class="step-title">{{ $t('organization.editor.howToGetCode') }}</div>
|
||||
<div class="step-list">
|
||||
<div class="step-item">
|
||||
<span class="step-number">1</span>
|
||||
<span class="step-text">{{ $t('organization.editor.step1') }}</span>
|
||||
</div>
|
||||
<div class="step-item">
|
||||
<span class="step-number">2</span>
|
||||
<span class="step-text">{{ $t('organization.editor.step2') }}</span>
|
||||
</div>
|
||||
<div class="step-item">
|
||||
<span class="step-number">3</span>
|
||||
<span class="step-text">{{ $t('organization.editor.step3') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮 -->
|
||||
<div class="settings-footer">
|
||||
<t-button theme="default" variant="outline" @click="handleClose">
|
||||
{{ $t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" @click="handleSubmit" :loading="submitting">
|
||||
{{ mode === 'create' ? $t('common.create') : $t('organization.join.preview') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<!-- 加入确认弹窗 -->
|
||||
<t-dialog
|
||||
v-model:visible="showJoinConfirm"
|
||||
:header="$t('organization.join.confirmTitle')"
|
||||
:confirm-btn="previewInfo?.is_already_member ? $t('common.close') : $t('organization.join.confirm')"
|
||||
:cancel-btn="previewInfo?.is_already_member ? null : $t('common.cancel')"
|
||||
:confirm-on-enter="!previewInfo?.is_already_member"
|
||||
@confirm="previewInfo?.is_already_member ? (showJoinConfirm = false) : confirmJoin()"
|
||||
@cancel="showJoinConfirm = false"
|
||||
:confirm-loading="joining"
|
||||
>
|
||||
<div v-if="previewInfo" class="join-confirm-content">
|
||||
<div class="org-preview-card">
|
||||
<div class="org-preview-header">
|
||||
<div class="org-avatar">
|
||||
<t-icon name="usergroup" size="24px" />
|
||||
</div>
|
||||
<div class="org-info">
|
||||
<h4 class="org-name">{{ previewInfo.name }}</h4>
|
||||
<p class="org-desc">{{ previewInfo.description || $t('organization.noDescription') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="org-stats">
|
||||
<div class="stat-item">
|
||||
<t-icon name="user" />
|
||||
<span>{{ $t('organization.join.memberCount', { count: previewInfo.member_count }) }}</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<t-icon name="folder" />
|
||||
<span>{{ $t('organization.join.shareCount', { count: previewInfo.share_count }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="previewInfo.is_already_member" class="already-member-notice">
|
||||
<t-icon name="check-circle-filled" />
|
||||
<span>{{ $t('organization.join.alreadyMember') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</t-dialog>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { OrganizationPreview } from '@/api/organization'
|
||||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const orgStore = useOrganizationStore()
|
||||
|
||||
// Props
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
mode: 'create' | 'join'
|
||||
}>()
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', value: boolean): void
|
||||
(e: 'success'): void
|
||||
}>()
|
||||
|
||||
const currentSection = ref<string>('basic')
|
||||
const submitting = ref(false)
|
||||
const showJoinConfirm = ref(false)
|
||||
const previewInfo = ref<OrganizationPreview | null>(null)
|
||||
const joining = ref(false)
|
||||
|
||||
const createForm = ref({
|
||||
name: '',
|
||||
description: ''
|
||||
})
|
||||
|
||||
const joinForm = ref({
|
||||
invite_code: ''
|
||||
})
|
||||
|
||||
// 计算属性
|
||||
const modalTitle = computed(() => {
|
||||
return props.mode === 'create'
|
||||
? t('organization.createOrg')
|
||||
: t('organization.joinOrg')
|
||||
})
|
||||
|
||||
const navItems = computed(() => {
|
||||
if (props.mode === 'create') {
|
||||
return [
|
||||
{ key: 'basic', icon: 'info-circle', label: t('organization.editor.navBasic') },
|
||||
{ key: 'permissions', icon: 'user-safety', label: t('organization.editor.navPermissions') }
|
||||
]
|
||||
} else {
|
||||
return [
|
||||
{ key: 'join', icon: 'user-add', label: t('organization.editor.navJoin') }
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
// 方法
|
||||
const resetForm = () => {
|
||||
createForm.value = { name: '', description: '' }
|
||||
joinForm.value = { invite_code: '' }
|
||||
currentSection.value = props.mode === 'create' ? 'basic' : 'join'
|
||||
showJoinConfirm.value = false
|
||||
previewInfo.value = null
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
emit('update:visible', false)
|
||||
setTimeout(resetForm, 300)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (props.mode === 'create') {
|
||||
await handleCreate()
|
||||
} else {
|
||||
await handleJoin()
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!createForm.value.name.trim()) {
|
||||
MessagePlugin.warning(t('organization.nameRequired'))
|
||||
currentSection.value = 'basic'
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await orgStore.create(
|
||||
createForm.value.name.trim(),
|
||||
createForm.value.description.trim()
|
||||
)
|
||||
if (result) {
|
||||
MessagePlugin.success(t('organization.createSuccess'))
|
||||
emit('success')
|
||||
handleClose()
|
||||
} else {
|
||||
MessagePlugin.error(orgStore.error || t('organization.createFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('organization.createFailed'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleJoin = async () => {
|
||||
if (!joinForm.value.invite_code.trim()) {
|
||||
MessagePlugin.warning(t('organization.inviteCodeRequired'))
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// First preview the organization
|
||||
const preview = await orgStore.preview(joinForm.value.invite_code.trim())
|
||||
if (preview) {
|
||||
previewInfo.value = preview
|
||||
showJoinConfirm.value = true
|
||||
} else {
|
||||
MessagePlugin.error(orgStore.error || t('organization.join.invalidCode'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('organization.join.invalidCode'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const confirmJoin = async () => {
|
||||
if (!joinForm.value.invite_code.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
joining.value = true
|
||||
try {
|
||||
const result = await orgStore.join(joinForm.value.invite_code.trim())
|
||||
if (result) {
|
||||
MessagePlugin.success(t('organization.joinSuccess'))
|
||||
showJoinConfirm.value = false
|
||||
emit('success')
|
||||
handleClose()
|
||||
} else {
|
||||
MessagePlugin.error(orgStore.error || t('organization.joinFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('organization.joinFailed'))
|
||||
} finally {
|
||||
joining.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 监听
|
||||
watch(() => props.visible, (newVal) => {
|
||||
if (newVal) {
|
||||
resetForm()
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => props.mode, () => {
|
||||
currentSection.value = props.mode === 'create' ? 'basic' : 'join'
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.settings-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.settings-modal {
|
||||
position: relative;
|
||||
width: 90vw;
|
||||
max-width: 900px;
|
||||
height: 80vh;
|
||||
max-height: 650px;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
|
||||
&.join-mode {
|
||||
max-width: 700px;
|
||||
max-height: 580px;
|
||||
}
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: none;
|
||||
background: #f5f5f5;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #666;
|
||||
transition: all 0.2s ease;
|
||||
z-index: 10;
|
||||
|
||||
&:hover {
|
||||
background: #e5e5e5;
|
||||
color: #000;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-container {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.settings-sidebar {
|
||||
width: 200px;
|
||||
background: #fafafa;
|
||||
border-right: 1px solid #e5e5e5;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
padding: 24px 20px;
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
margin: 0;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.settings-nav {
|
||||
flex: 1;
|
||||
padding: 12px 8px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 4px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
color: #00000099;
|
||||
|
||||
&:hover {
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: #07c05f1a;
|
||||
color: #07c05f;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
margin-right: 8px;
|
||||
font-size: 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 24px 32px;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.section-content {
|
||||
.section-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 0 0 8px 0;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.section-desc {
|
||||
margin: 0;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
color: #00000066;
|
||||
line-height: 22px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-item {
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-family: "PingFang SC";
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
|
||||
&.required::after {
|
||||
content: '*';
|
||||
color: #FA5151;
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.form-tip {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.name-input-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.name-input-wrapper .name-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// 权限说明样式
|
||||
.permissions-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.permission-card {
|
||||
background: #fafafa;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
border: 1px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.permission-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.permission-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #fff;
|
||||
|
||||
&.admin {
|
||||
background: linear-gradient(135deg, #07c05f, #05a04f);
|
||||
}
|
||||
|
||||
&.editor {
|
||||
background: linear-gradient(135deg, #f5a623, #e09612);
|
||||
}
|
||||
|
||||
&.viewer {
|
||||
background: linear-gradient(135deg, #909399, #606266);
|
||||
}
|
||||
}
|
||||
|
||||
.permission-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.role-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #000000e6;
|
||||
}
|
||||
}
|
||||
|
||||
.permission-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 0;
|
||||
font-size: 13px;
|
||||
color: #00000099;
|
||||
}
|
||||
|
||||
.check-icon {
|
||||
color: #07c05f;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.close-icon {
|
||||
color: #FA5151;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.info-notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
margin-top: 20px;
|
||||
padding: 12px 16px;
|
||||
background: #e8f4ff;
|
||||
border-radius: 8px;
|
||||
color: #0052d9;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
|
||||
.t-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
// 加入组织样式
|
||||
.join-illustration {
|
||||
text-align: center;
|
||||
padding: 24px 0 32px;
|
||||
|
||||
.illustration-icon {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
margin: 0 auto 16px;
|
||||
background: linear-gradient(135deg, #07c05f1a, #07c05f0d);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #07c05f;
|
||||
}
|
||||
|
||||
.illustration-text {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: #00000066;
|
||||
}
|
||||
}
|
||||
|
||||
.invite-code-input {
|
||||
:deep(.t-input__inner) {
|
||||
font-size: 16px;
|
||||
letter-spacing: 1px;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.join-steps {
|
||||
margin-top: 32px;
|
||||
padding: 20px;
|
||||
background: #fafafa;
|
||||
border-radius: 8px;
|
||||
|
||||
.step-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.step-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.step-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background: #07c05f;
|
||||
color: #fff;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-text {
|
||||
font-size: 13px;
|
||||
color: #00000099;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-footer {
|
||||
padding: 16px 32px;
|
||||
border-top: 1px solid #e5e5e5;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// 过渡动画
|
||||
.modal-enter-active,
|
||||
.modal-leave-active {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.modal-enter-from,
|
||||
.modal-leave-to {
|
||||
opacity: 0;
|
||||
|
||||
.settings-modal {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
}
|
||||
|
||||
// 加入确认弹窗样式
|
||||
.join-confirm-content {
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.org-preview-card {
|
||||
background: #fafafa;
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
border: 1px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.org-preview-header {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.org-avatar {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
background: linear-gradient(135deg, #07c05f, #05a04f);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.org-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.org-name {
|
||||
margin: 0 0 4px 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.org-desc {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: #00000066;
|
||||
line-height: 20px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.org-stats {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid #e5e5e5;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: #00000099;
|
||||
|
||||
.t-icon {
|
||||
font-size: 16px;
|
||||
color: #00000066;
|
||||
}
|
||||
}
|
||||
|
||||
.already-member-notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
padding: 12px 16px;
|
||||
background: #e8f4ff;
|
||||
border-radius: 8px;
|
||||
color: #0052d9;
|
||||
font-size: 14px;
|
||||
|
||||
.t-icon {
|
||||
font-size: 18px;
|
||||
color: #07c05f;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -369,7 +369,8 @@ func (t *DataAnalysisTool) LoadFromKnowledge(ctx context.Context, knowledge *typ
|
|||
// - *TableSchema: schema information of the created table
|
||||
// - error: any error that occurred during the operation
|
||||
func (t *DataAnalysisTool) LoadFromKnowledgeID(ctx context.Context, knowledgeID string) (*TableSchema, error) {
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
|
||||
// Use GetKnowledgeByIDOnly to support cross-tenant shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][DataAnalysis] Failed to get knowledge by ID '%s': %v", knowledgeID, err)
|
||||
return nil, fmt.Errorf("failed to get knowledge by ID: %w", err)
|
||||
|
|
|
|||
|
|
@ -49,8 +49,8 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
|||
}, err
|
||||
}
|
||||
|
||||
// Get knowledge to get TenantID
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, input.KnowledgeID)
|
||||
// Get knowledge to get TenantID (use IDOnly to support cross-tenant shared KB)
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, input.KnowledgeID)
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
|
|
|
|||
|
|
@ -54,27 +54,25 @@ type GetDocumentInfoTool struct {
|
|||
BaseTool
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewGetDocumentInfoTool creates a new get document info tool
|
||||
func NewGetDocumentInfoTool(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
searchTargets types.SearchTargets,
|
||||
) *GetDocumentInfoTool {
|
||||
return &GetDocumentInfoTool{
|
||||
BaseTool: getDocumentInfoTool,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
// Execute retrieves document information with concurrent processing
|
||||
func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
|
||||
// Parse args from json.RawMessage
|
||||
var input GetDocumentInfoInput
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
|
|
@ -118,8 +116,8 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
|
|||
go func(id string) {
|
||||
defer wg.Done()
|
||||
|
||||
// Get knowledge metadata
|
||||
knowledge, err := t.knowledgeService.GetRepository().GetKnowledgeByID(ctx, tenantID, id)
|
||||
// Get knowledge metadata without tenant filter to support shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
|
|
@ -129,9 +127,19 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
|
|||
return
|
||||
}
|
||||
|
||||
// Get chunk count
|
||||
// Verify the knowledge's KB is in searchTargets (permission check)
|
||||
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
err: fmt.Errorf("知识库 %s 不可访问", knowledge.KnowledgeBaseID),
|
||||
}
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Use knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
|
||||
_, total, err := t.chunkService.GetRepository().
|
||||
ListPagedChunksByKnowledgeID(ctx, tenantID, id, &types.Pagination{
|
||||
ListPagedChunksByKnowledgeID(ctx, knowledge.TenantID, id, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1000,
|
||||
}, []types.ChunkType{"text"}, "", "", "", "", "")
|
||||
|
|
|
|||
|
|
@ -94,18 +94,16 @@ type GrepChunksInput struct {
|
|||
// Similar to grep command in Unix-like systems, but operates on knowledge base content
|
||||
type GrepChunksTool struct {
|
||||
BaseTool
|
||||
db *gorm.DB
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string // Specific knowledge/document IDs to search within
|
||||
db *gorm.DB
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewGrepChunksTool creates a new grep chunks tool
|
||||
func NewGrepChunksTool(db *gorm.DB, knowledgeBaseIDs []string, knowledgeIDs []string) *GrepChunksTool {
|
||||
func NewGrepChunksTool(db *gorm.DB, searchTargets types.SearchTargets) *GrepChunksTool {
|
||||
return &GrepChunksTool{
|
||||
BaseTool: grepChunksTool,
|
||||
db: db,
|
||||
knowledgeBaseIDs: knowledgeBaseIDs,
|
||||
knowledgeIDs: knowledgeIDs,
|
||||
BaseTool: grepChunksTool,
|
||||
db: db,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -148,27 +146,38 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args json.RawMessage) (*ty
|
|||
}
|
||||
}
|
||||
|
||||
// Parse knowledge_base_ids filter
|
||||
kbIDs := input.KnowledgeBaseIDs
|
||||
if len(kbIDs) == 0 {
|
||||
kbIDs = t.knowledgeBaseIDs
|
||||
// Get allowed KBs from searchTargets
|
||||
allowedKBIDs := t.searchTargets.GetAllKnowledgeBaseIDs()
|
||||
kbTenantMap := t.searchTargets.GetKBTenantMap()
|
||||
|
||||
// Collect all specific knowledge IDs from searchTargets
|
||||
var allowedKnowledgeIDs []string
|
||||
for _, target := range t.searchTargets {
|
||||
if target.Type == types.SearchTargetTypeKnowledge && len(target.KnowledgeIDs) > 0 {
|
||||
allowedKnowledgeIDs = append(allowedKnowledgeIDs, target.KnowledgeIDs...)
|
||||
}
|
||||
}
|
||||
|
||||
// // Parse knowledge_ids filter
|
||||
// var knowledgeIDs []string
|
||||
// if knowledgeIDsRaw, ok := args["knowledge_ids"].([]interface{}); ok {
|
||||
// for _, id := range knowledgeIDsRaw {
|
||||
// if idStr, ok := id.(string); ok && idStr != "" {
|
||||
// knowledgeIDs = append(knowledgeIDs, idStr)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// Parse knowledge_base_ids filter from input
|
||||
kbIDs := input.KnowledgeBaseIDs
|
||||
if len(kbIDs) == 0 {
|
||||
kbIDs = allowedKBIDs
|
||||
} else {
|
||||
// Validate input KBs against allowed KBs
|
||||
validKBs := make([]string, 0)
|
||||
for _, kbID := range kbIDs {
|
||||
if t.searchTargets.ContainsKB(kbID) {
|
||||
validKBs = append(validKBs, kbID)
|
||||
}
|
||||
}
|
||||
kbIDs = validKBs
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KnowledgeIDs: %v",
|
||||
patterns, maxResults, t.knowledgeIDs)
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Patterns: %v, MaxResults: %d, KBs: %v, KnowledgeIDs: %v, KBTenantMap: %v",
|
||||
patterns, maxResults, kbIDs, allowedKnowledgeIDs, kbTenantMap)
|
||||
|
||||
// Build and execute query
|
||||
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, t.knowledgeIDs)
|
||||
// Build and execute query with tenant info
|
||||
results, totalCount, err := t.searchChunks(ctx, patterns, kbIDs, allowedKnowledgeIDs, kbTenantMap)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][GrepChunks] Search failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
|
|
@ -256,32 +265,53 @@ type chunkWithTitle struct {
|
|||
}
|
||||
|
||||
// searchChunks performs the database search with pattern matching
|
||||
// kbTenantMap provides KB-to-tenant mapping for cross-tenant queries
|
||||
func (t *GrepChunksTool) searchChunks(
|
||||
ctx context.Context,
|
||||
patterns []string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
kbTenantMap map[string]uint64,
|
||||
) ([]chunkWithTitle, int64, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
// Safety check: must have either kbIDs or knowledgeIDs
|
||||
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
logger.Warnf(ctx, "[Tool][GrepChunks] No kbIDs or knowledgeIDs specified, returning empty results")
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
// Build base query
|
||||
// Use knowledge_base_id filter combined with tenant_id to ensure data isolation
|
||||
query := t.db.Debug().WithContext(ctx).Table("chunks").
|
||||
Select("chunks.id, chunks.content, chunks.chunk_index, chunks.knowledge_id, chunks.knowledge_base_id, chunks.chunk_type, chunks.created_at, knowledges.title as knowledge_title, COUNT(*) OVER (PARTITION BY chunks.knowledge_id) AS total_chunk_count").
|
||||
Joins("LEFT JOIN knowledges ON chunks.knowledge_id = knowledges.id").
|
||||
Where("chunks.tenant_id = ?", tenantID).
|
||||
Where("chunks.is_enabled = ?", true).
|
||||
Where("chunks.deleted_at IS NULL").
|
||||
Where("knowledges.deleted_at IS NULL")
|
||||
|
||||
// Apply knowledge IDs filter (specific documents) - takes priority over KB filter
|
||||
// Build tenant-aware KB filter: (kb_id = X AND tenant_id = Y) OR (kb_id = Z AND tenant_id = W) ...
|
||||
// This ensures we only access chunks from KBs we have permission for, with correct tenant scope
|
||||
if len(knowledgeIDs) > 0 {
|
||||
// For specific knowledge IDs, filter directly by knowledge_id
|
||||
// Permission already checked when building searchTargets
|
||||
query = query.Where("chunks.knowledge_id IN ?", knowledgeIDs)
|
||||
logger.Infof(ctx, "[Tool][GrepChunks] Filtering by %d specific knowledge IDs", len(knowledgeIDs))
|
||||
} else if len(kbIDs) > 0 {
|
||||
// Apply knowledge base filter only if no specific knowledge IDs
|
||||
query = query.Where("chunks.knowledge_base_id IN ?", kbIDs)
|
||||
// Build OR conditions for each KB with its tenant
|
||||
var conditions []string
|
||||
var args []interface{}
|
||||
for _, kbID := range kbIDs {
|
||||
tenantID := kbTenantMap[kbID]
|
||||
if tenantID > 0 {
|
||||
conditions = append(conditions, "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)")
|
||||
args = append(args, kbID, tenantID)
|
||||
}
|
||||
}
|
||||
if len(conditions) > 0 {
|
||||
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
|
||||
} else {
|
||||
logger.Warnf(ctx, "[Tool][GrepChunks] No valid KB-tenant pairs found")
|
||||
return nil, 0, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Apply pattern matching (case-insensitive fixed string matching, OR logic for multiple patterns)
|
||||
|
|
|
|||
|
|
@ -965,10 +965,6 @@ func (t *KnowledgeSearchTool) formatOutput(
|
|||
kbsToSearch []string,
|
||||
queries []string,
|
||||
) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
if len(results) == 0 {
|
||||
data := map[string]interface{}{
|
||||
"knowledge_base_ids": kbsToSearch,
|
||||
|
|
@ -1052,22 +1048,30 @@ func (t *KnowledgeSearchTool) formatOutput(
|
|||
output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle)
|
||||
|
||||
// Get total chunk count for this knowledge (cache it)
|
||||
// Use KB's tenant_id from searchTargets to support cross-tenant shared KB
|
||||
if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists {
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
tenantID, result.KnowledgeID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
|
||||
result.KnowledgeID,
|
||||
err,
|
||||
)
|
||||
// Get tenant_id from searchTargets using the KB ID from the result
|
||||
effectiveTenantID := t.searchTargets.GetTenantIDForKB(result.KnowledgeBaseID)
|
||||
if effectiveTenantID == 0 {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
knowledgeTotalMap[result.KnowledgeID] = total
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
effectiveTenantID, result.KnowledgeID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "", "", "", "", "",
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
|
||||
result.KnowledgeID,
|
||||
err,
|
||||
)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
knowledgeTotalMap[result.KnowledgeID] = total
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,27 +67,25 @@ type ListKnowledgeChunksTool struct {
|
|||
BaseTool
|
||||
chunkService interfaces.ChunkService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
searchTargets types.SearchTargets // Pre-computed unified search targets with KB-tenant mapping
|
||||
}
|
||||
|
||||
// NewListKnowledgeChunksTool creates a new tool instance.
|
||||
func NewListKnowledgeChunksTool(
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
searchTargets types.SearchTargets,
|
||||
) *ListKnowledgeChunksTool {
|
||||
return &ListKnowledgeChunksTool{
|
||||
BaseTool: listKnowledgeChunksTool,
|
||||
chunkService: chunkService,
|
||||
knowledgeService: knowledgeService,
|
||||
searchTargets: searchTargets,
|
||||
}
|
||||
}
|
||||
|
||||
// Execute performs the chunk fetch against the chunk service.
|
||||
func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
|
||||
// Parse args from json.RawMessage
|
||||
var input ListKnowledgeChunksInput
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
|
|
@ -107,6 +105,26 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
|||
}
|
||||
knowledgeID = strings.TrimSpace(knowledgeID)
|
||||
|
||||
// Get knowledge info without tenant filter to support shared KB
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Knowledge not found: %v", err),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Verify the knowledge's KB is in searchTargets (permission check)
|
||||
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Knowledge base %s is not accessible", knowledge.KnowledgeBaseID),
|
||||
}, fmt.Errorf("knowledge base not in search targets")
|
||||
}
|
||||
|
||||
// Use the knowledge's actual tenant_id for chunk query (supports cross-tenant shared KB)
|
||||
effectiveTenantID := knowledge.TenantID
|
||||
|
||||
chunkLimit := 20
|
||||
if input.Limit > 0 {
|
||||
chunkLimit = input.Limit
|
||||
|
|
@ -125,7 +143,7 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
|||
}
|
||||
|
||||
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx,
|
||||
tenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
|
||||
effectiveTenantID, knowledgeID, pagination, []types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ}, "", "", "", "", "")
|
||||
if err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
|
|
@ -206,11 +224,12 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess
|
|||
}
|
||||
|
||||
// lookupKnowledgeTitle looks up the title of a knowledge document
|
||||
// Uses GetKnowledgeByIDOnly to support cross-tenant shared KB
|
||||
func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, knowledgeID string) string {
|
||||
if t.knowledgeService == nil {
|
||||
return ""
|
||||
}
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByID(ctx, knowledgeID)
|
||||
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil || knowledge == nil {
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,18 @@ func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint64, id
|
|||
return &chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly retrieves a chunk by ID without tenant filter (for permission resolution).
|
||||
func (r *chunkRepository) GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error) {
|
||||
var chunk types.Chunk
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&chunk).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("chunk not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkBySeqID retrieves a chunk by its seq_id and tenant ID
|
||||
func (r *chunkRepository) GetChunkBySeqID(ctx context.Context, tenantID uint64, seqID int64) (*types.Chunk, error) {
|
||||
var chunk types.Chunk
|
||||
|
|
@ -69,6 +81,18 @@ func (r *chunkRepository) ListChunksByID(
|
|||
return chunks, nil
|
||||
}
|
||||
|
||||
// ListChunksByIDOnly retrieves multiple chunks by their IDs without tenant filter (for shared KB resolution).
|
||||
func (r *chunkRepository) ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// ListChunksBySeqID retrieves multiple chunks by their seq_ids
|
||||
func (r *chunkRepository) ListChunksBySeqID(
|
||||
ctx context.Context, tenantID uint64, seqIDs []int64,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,187 @@
|
|||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrKBShareNotFound = errors.New("knowledge base share not found")
|
||||
ErrKBShareAlreadyExists = errors.New("knowledge base already shared to this organization")
|
||||
)
|
||||
|
||||
// kbShareRepository implements KBShareRepository interface
|
||||
type kbShareRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewKBShareRepository creates a new knowledge base share repository
|
||||
func NewKBShareRepository(db *gorm.DB) interfaces.KBShareRepository {
|
||||
return &kbShareRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new share record
|
||||
func (r *kbShareRepository) Create(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
// Check if share already exists
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND organization_id = ? AND deleted_at IS NULL", share.KnowledgeBaseID, share.OrganizationID).
|
||||
Count(&count)
|
||||
|
||||
if count > 0 {
|
||||
return ErrKBShareAlreadyExists
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(share).Error
|
||||
}
|
||||
|
||||
// GetByID gets a share record by ID
|
||||
func (r *kbShareRepository) GetByID(ctx context.Context, id string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// GetByKBAndOrg gets a share record by knowledge base ID and organization ID
|
||||
func (r *kbShareRepository) GetByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) {
|
||||
var share types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ? AND organization_id = ?", kbID, orgID).
|
||||
First(&share).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKBShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
// Update updates a share record
|
||||
func (r *kbShareRepository) Update(ctx context.Context, share *types.KnowledgeBaseShare) error {
|
||||
return r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("id = ?", share.ID).
|
||||
Updates(share).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes a share record
|
||||
func (r *kbShareRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeBaseID soft deletes all share records for a knowledge base (e.g. when the KB is deleted)
|
||||
func (r *kbShareRepository) DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error {
|
||||
return r.db.WithContext(ctx).Where("knowledge_base_id = ?", kbID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// DeleteByOrganizationID soft deletes all share records for an organization (e.g. when the org is deleted)
|
||||
func (r *kbShareRepository) DeleteByOrganizationID(ctx context.Context, orgID string) error {
|
||||
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.KnowledgeBaseShare{}).Error
|
||||
}
|
||||
|
||||
// ListByKnowledgeBase lists all share records for a knowledge base
|
||||
func (r *kbShareRepository) ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("Organization").
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Order("created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// ListByOrganization lists all share records for an organization
|
||||
func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("KnowledgeBase").
|
||||
Where("organization_id = ?", orgID).
|
||||
Order("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 so users no longer see KBs after the space is deleted.
|
||||
func (r *kbShareRepository) ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
var shares []*types.KnowledgeBaseShare
|
||||
|
||||
// Get shares for organizations that the user is a member of; exclude deleted organizations
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("KnowledgeBase").
|
||||
Preload("Organization").
|
||||
Joins("JOIN organization_members ON organization_members.organization_id = kb_shares.organization_id").
|
||||
Joins("JOIN organizations ON organizations.id = kb_shares.organization_id AND organizations.deleted_at IS NULL").
|
||||
Where("organization_members.user_id = ?", userID).
|
||||
Where("kb_shares.deleted_at IS NULL").
|
||||
Order("kb_shares.created_at DESC").
|
||||
Find(&shares).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseID counts the number of organizations a knowledge base is shared with
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Where("knowledge_base_id = ? AND deleted_at IS NULL", kbID).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseIDs counts the number of shares for multiple knowledge bases at once
|
||||
func (r *kbShareRepository) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
if len(kbIDs) == 0 {
|
||||
return make(map[string]int64), nil
|
||||
}
|
||||
|
||||
type result struct {
|
||||
KnowledgeBaseID string `gorm:"column:knowledge_base_id"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
|
||||
var results []result
|
||||
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
|
||||
Select("knowledge_base_id, COUNT(*) as count").
|
||||
Where("knowledge_base_id IN ? AND deleted_at IS NULL", kbIDs).
|
||||
Group("knowledge_base_id").
|
||||
Find(&results).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
countMap := make(map[string]int64)
|
||||
for _, r := range results {
|
||||
countMap[r.KnowledgeBaseID] = r.Count
|
||||
}
|
||||
return countMap, nil
|
||||
}
|
||||
|
|
@ -47,6 +47,18 @@ func (r *knowledgeRepository) GetKnowledgeByID(
|
|||
return &knowledge, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
|
||||
func (r *knowledgeRepository) GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) {
|
||||
var knowledge types.Knowledge
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&knowledge).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrKnowledgeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &knowledge, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
|
||||
func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context, tenantID uint64, kbID string,
|
||||
|
|
@ -402,6 +414,111 @@ func (r *knowledgeRepository) SearchKnowledge(
|
|||
return knowledges, hasMore, nil
|
||||
}
|
||||
|
||||
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (e.g. own + shared KBs).
|
||||
func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
ctx context.Context,
|
||||
scopes []types.KnowledgeSearchScope,
|
||||
keyword string,
|
||||
offset, limit int,
|
||||
fileTypes []string,
|
||||
) ([]*types.Knowledge, bool, error) {
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
type KnowledgeWithKBName struct {
|
||||
types.Knowledge
|
||||
KnowledgeBaseName string `gorm:"column:knowledge_base_name"`
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(scopes))
|
||||
args := make([]interface{}, 0, len(scopes)*2)
|
||||
for i, s := range scopes {
|
||||
placeholders[i] = "(?,?)"
|
||||
args = append(args, s.TenantID, s.KBID)
|
||||
}
|
||||
scopeCondition := "(knowledges.tenant_id, knowledges.knowledge_base_id) IN (" + strings.Join(placeholders, ",") + ")"
|
||||
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("knowledges").
|
||||
Select("knowledges.*, knowledge_bases.name as knowledge_base_name").
|
||||
Joins("JOIN knowledge_bases ON knowledge_bases.id = knowledges.knowledge_base_id AND knowledge_bases.tenant_id = knowledges.tenant_id").
|
||||
Where(scopeCondition, args...).
|
||||
Where("knowledge_bases.type = ?", types.KnowledgeBaseTypeDocument).
|
||||
Where("knowledges.deleted_at IS NULL")
|
||||
|
||||
if keyword != "" {
|
||||
query = query.Where("knowledges.file_name LIKE ?", "%"+keyword+"%")
|
||||
}
|
||||
|
||||
if len(fileTypes) > 0 {
|
||||
seen := make(map[string]bool)
|
||||
var uniquePatterns []string
|
||||
for _, ft := range fileTypes {
|
||||
ft = strings.ToLower(strings.TrimPrefix(ft, "."))
|
||||
pattern := "%." + ft
|
||||
if !seen[pattern] {
|
||||
seen[pattern] = true
|
||||
uniquePatterns = append(uniquePatterns, pattern)
|
||||
}
|
||||
var aliases []string
|
||||
switch ft {
|
||||
case "xlsx":
|
||||
aliases = []string{"%.xls"}
|
||||
case "xls":
|
||||
aliases = []string{"%.xlsx"}
|
||||
case "docx":
|
||||
aliases = []string{"%.doc"}
|
||||
case "doc":
|
||||
aliases = []string{"%.docx"}
|
||||
case "jpg":
|
||||
aliases = []string{"%.jpeg", "%.png"}
|
||||
case "jpeg":
|
||||
aliases = []string{"%.jpg", "%.png"}
|
||||
case "png":
|
||||
aliases = []string{"%.jpg", "%.jpeg"}
|
||||
}
|
||||
for _, alias := range aliases {
|
||||
if !seen[alias] {
|
||||
seen[alias] = true
|
||||
uniquePatterns = append(uniquePatterns, alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(uniquePatterns) > 0 {
|
||||
orConditions := make([]string, len(uniquePatterns))
|
||||
ftArgs := make([]interface{}, len(uniquePatterns))
|
||||
for i, p := range uniquePatterns {
|
||||
orConditions[i] = "LOWER(knowledges.file_name) LIKE ?"
|
||||
ftArgs[i] = p
|
||||
}
|
||||
query = query.Where("("+strings.Join(orConditions, " OR ")+")", ftArgs...)
|
||||
}
|
||||
}
|
||||
|
||||
var results []KnowledgeWithKBName
|
||||
err := query.Order("knowledges.created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit + 1).
|
||||
Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
hasMore := len(results) > limit
|
||||
if hasMore {
|
||||
results = results[:limit]
|
||||
}
|
||||
|
||||
knowledges := make([]*types.Knowledge, len(results))
|
||||
for i, r := range results {
|
||||
k := r.Knowledge
|
||||
k.KnowledgeBaseName = r.KnowledgeBaseName
|
||||
knowledges[i] = &k
|
||||
}
|
||||
return knowledges, hasMore, nil
|
||||
}
|
||||
|
||||
// ListIDsByTagID returns all knowledge IDs that have the specified tag ID
|
||||
func (r *knowledgeRepository) ListIDsByTagID(
|
||||
ctx context.Context,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,285 @@
|
|||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrOrganizationNotFound = errors.New("organization not found")
|
||||
ErrOrgMemberNotFound = errors.New("organization member not found")
|
||||
ErrOrgMemberAlreadyExists = errors.New("member already exists in organization")
|
||||
ErrInviteCodeNotFound = errors.New("invite code not found")
|
||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||
)
|
||||
|
||||
// organizationRepository implements OrganizationRepository interface
|
||||
type organizationRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrganizationRepository creates a new organization repository
|
||||
func NewOrganizationRepository(db *gorm.DB) interfaces.OrganizationRepository {
|
||||
return &organizationRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new organization
|
||||
func (r *organizationRepository) Create(ctx context.Context, org *types.Organization) error {
|
||||
return r.db.WithContext(ctx).Create(org).Error
|
||||
}
|
||||
|
||||
// GetByID gets an organization by ID
|
||||
func (r *organizationRepository) GetByID(ctx context.Context, id string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrganizationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// GetByInviteCode gets an organization by invite code (returns ErrInviteCodeExpired if code has expired)
|
||||
func (r *organizationRepository) GetByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) {
|
||||
var org types.Organization
|
||||
if err := r.db.WithContext(ctx).Where("invite_code = ?", inviteCode).First(&org).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrInviteCodeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if org.InviteCodeExpiresAt != nil && org.InviteCodeExpiresAt.Before(time.Now()) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return &org, nil
|
||||
}
|
||||
|
||||
// ListByUserID lists organizations that a user belongs to
|
||||
func (r *organizationRepository) ListByUserID(ctx context.Context, userID string) ([]*types.Organization, error) {
|
||||
var orgs []*types.Organization
|
||||
|
||||
// Get organizations where user is a member
|
||||
err := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_members ON organization_members.organization_id = organizations.id").
|
||||
Where("organization_members.user_id = ?", userID).
|
||||
Order("organizations.created_at DESC").
|
||||
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").
|
||||
Updates(org).Error
|
||||
}
|
||||
|
||||
// Delete soft deletes an organization
|
||||
func (r *organizationRepository) Delete(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Organization{}).Error
|
||||
}
|
||||
|
||||
// AddMember adds a member to an organization
|
||||
func (r *organizationRepository) AddMember(ctx context.Context, member *types.OrganizationMember) error {
|
||||
// Check if member already exists
|
||||
var count int64
|
||||
r.db.WithContext(ctx).Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ? AND user_id = ?", member.OrganizationID, member.UserID).
|
||||
Count(&count)
|
||||
|
||||
if count > 0 {
|
||||
return ErrOrgMemberAlreadyExists
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(member).Error
|
||||
}
|
||||
|
||||
// RemoveMember removes a member from an organization
|
||||
func (r *organizationRepository) RemoveMember(ctx context.Context, orgID string, userID string) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
Delete(&types.OrganizationMember{})
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateMemberRole updates a member's role in an organization
|
||||
func (r *organizationRepository) UpdateMemberRole(ctx context.Context, orgID string, userID string, role types.OrgMemberRole) error {
|
||||
result := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
Update("role", role)
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrOrgMemberNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMembers lists all members of an organization
|
||||
func (r *organizationRepository) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
||||
var members []*types.OrganizationMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("organization_id = ?", orgID).
|
||||
Order("created_at ASC").
|
||||
Find(&members).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// GetMember gets a specific member of an organization
|
||||
func (r *organizationRepository) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
||||
var member types.OrganizationMember
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ?", orgID, userID).
|
||||
First(&member).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrOrgMemberNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &member, nil
|
||||
}
|
||||
|
||||
// CountMembers counts the number of members in an organization
|
||||
func (r *organizationRepository) CountMembers(ctx context.Context, orgID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationMember{}).
|
||||
Where("organization_id = ?", orgID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateInviteCode updates the invite code and optional expiry for an organization (expiresAt nil = never expire)
|
||||
func (r *organizationRepository) UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error {
|
||||
updates := map[string]interface{}{"invite_code": inviteCode, "invite_code_expires_at": expiresAt}
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.Organization{}).
|
||||
Where("id = ?", orgID).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
// ----------------
|
||||
// Join Requests
|
||||
// ----------------
|
||||
|
||||
var ErrJoinRequestNotFound = errors.New("join request not found")
|
||||
|
||||
// CreateJoinRequest creates a new join request
|
||||
func (r *organizationRepository) CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error {
|
||||
return r.db.WithContext(ctx).Create(request).Error
|
||||
}
|
||||
|
||||
// GetJoinRequestByID gets a join request by ID
|
||||
func (r *organizationRepository) GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("id = ?", id).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingJoinRequest gets a pending join request for a user in an organization (any type)
|
||||
func (r *organizationRepository) GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ? AND status = ?", orgID, userID, types.JoinRequestStatusPending).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// GetPendingRequestByType gets a pending request for a user filtered by request type
|
||||
func (r *organizationRepository) GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error) {
|
||||
var request types.OrganizationJoinRequest
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("organization_id = ? AND user_id = ? AND status = ? AND request_type = ?", orgID, userID, types.JoinRequestStatusPending, requestType).
|
||||
First(&request).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
// ListJoinRequests lists join requests for an organization
|
||||
func (r *organizationRepository) ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error) {
|
||||
var requests []*types.OrganizationJoinRequest
|
||||
query := r.db.WithContext(ctx).
|
||||
Preload("User").
|
||||
Where("organization_id = ?", orgID)
|
||||
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
err := query.Order("created_at DESC").Find(&requests).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return requests, nil
|
||||
}
|
||||
|
||||
// CountJoinRequests counts join requests for an organization by status
|
||||
func (r *organizationRepository) CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.WithContext(ctx).Model(&types.OrganizationJoinRequest{}).Where("organization_id = ?", orgID)
|
||||
if status != "" {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// UpdateJoinRequestStatus updates the status of a join request
|
||||
func (r *organizationRepository) UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.OrganizationJoinRequest{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"status": status,
|
||||
"reviewed_by": reviewedBy,
|
||||
"reviewed_at": gorm.Expr("NOW()"),
|
||||
"review_message": reviewMessage,
|
||||
}).Error
|
||||
}
|
||||
|
|
@ -95,6 +95,28 @@ func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*t
|
|||
return users, nil
|
||||
}
|
||||
|
||||
// SearchUsers searches users by username or email
|
||||
func (r *userRepository) SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error) {
|
||||
var users []*types.User
|
||||
searchPattern := "%" + query + "%"
|
||||
|
||||
dbQuery := r.db.WithContext(ctx).
|
||||
Where("username ILIKE ? OR email ILIKE ?", searchPattern, searchPattern).
|
||||
Where("is_active = ?", true).
|
||||
Order("username ASC")
|
||||
|
||||
if limit > 0 {
|
||||
dbQuery = dbQuery.Limit(limit)
|
||||
} else {
|
||||
dbQuery = dbQuery.Limit(20) // default limit
|
||||
}
|
||||
|
||||
if err := dbQuery.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// authTokenRepository implements auth token repository interface
|
||||
type authTokenRepository struct {
|
||||
db *gorm.DB
|
||||
|
|
|
|||
|
|
@ -366,14 +366,14 @@ func (s *agentService) registerTools(
|
|||
s.cfg,
|
||||
)
|
||||
case tools.ToolGrepChunks:
|
||||
toolToRegister = tools.NewGrepChunksTool(s.db, config.KnowledgeBases, config.KnowledgeIDs)
|
||||
logger.Infof(ctx, "Registered grep_chunks tool, KBs: %d, KnowledgeIDs: %d", len(config.KnowledgeBases), len(config.KnowledgeIDs))
|
||||
toolToRegister = tools.NewGrepChunksTool(s.db, config.SearchTargets)
|
||||
logger.Infof(ctx, "Registered grep_chunks tool with searchTargets: %d targets", len(config.SearchTargets))
|
||||
case tools.ToolListKnowledgeChunks:
|
||||
toolToRegister = tools.NewListKnowledgeChunksTool(s.knowledgeService, s.chunkService)
|
||||
toolToRegister = tools.NewListKnowledgeChunksTool(s.knowledgeService, s.chunkService, config.SearchTargets)
|
||||
case tools.ToolQueryKnowledgeGraph:
|
||||
toolToRegister = tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService)
|
||||
case tools.ToolGetDocumentInfo:
|
||||
toolToRegister = tools.NewGetDocumentInfoTool(s.knowledgeService, s.chunkService)
|
||||
toolToRegister = tools.NewGetDocumentInfoTool(s.knowledgeService, s.chunkService, config.SearchTargets)
|
||||
case tools.ToolDatabaseQuery:
|
||||
toolToRegister = tools.NewDatabaseQueryTool(s.db)
|
||||
case tools.ToolWebSearch:
|
||||
|
|
|
|||
|
|
@ -100,6 +100,19 @@ func (s *chunkService) GetChunkByID(ctx context.Context, id string) (*types.Chun
|
|||
return chunk, nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly retrieves a chunk by ID without tenant filter (for permission resolution).
|
||||
func (s *chunkService) GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error) {
|
||||
chunk, err := s.chunkRepository.GetChunkByIDOnly(ctx, id)
|
||||
if err != nil {
|
||||
if err != nil && err.Error() == "chunk not found" {
|
||||
return nil, ErrChunkNotFound
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"chunk_id": id})
|
||||
return nil, err
|
||||
}
|
||||
return chunk, nil
|
||||
}
|
||||
|
||||
// ListChunksByKnowledgeID lists all chunks for a knowledge ID
|
||||
// This method retrieves all chunks belonging to a specific knowledge document
|
||||
// Parameters:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,379 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrShareNotFound = errors.New("share not found")
|
||||
ErrSharePermissionDenied = errors.New("permission denied for this share operation")
|
||||
ErrKBNotFound = errors.New("knowledge base not found")
|
||||
ErrNotKBOwner = errors.New("only knowledge base owner can share")
|
||||
// ErrOrgRoleCannotShare: only editors and admins in the org can share KBs to that org; viewers cannot
|
||||
ErrOrgRoleCannotShare = errors.New("only editors and admins can share knowledge bases to this organization")
|
||||
)
|
||||
|
||||
// kbShareService implements KBShareService interface
|
||||
type kbShareService struct {
|
||||
shareRepo interfaces.KBShareRepository
|
||||
orgRepo interfaces.OrganizationRepository
|
||||
kbRepo interfaces.KnowledgeBaseRepository
|
||||
kgRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
}
|
||||
|
||||
// NewKBShareService creates a new knowledge base share service
|
||||
func NewKBShareService(
|
||||
shareRepo interfaces.KBShareRepository,
|
||||
orgRepo interfaces.OrganizationRepository,
|
||||
kbRepo interfaces.KnowledgeBaseRepository,
|
||||
kgRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
) interfaces.KBShareService {
|
||||
return &kbShareService{
|
||||
shareRepo: shareRepo,
|
||||
orgRepo: orgRepo,
|
||||
kbRepo: kbRepo,
|
||||
kgRepo: kgRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// ShareKnowledgeBase shares a knowledge base to an organization
|
||||
func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error) {
|
||||
logger.Infof(ctx, "Sharing knowledge base %s to organization %s", kbID, orgID)
|
||||
|
||||
// Verify knowledge base exists and user is the owner (same tenant)
|
||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, ErrKBNotFound
|
||||
}
|
||||
|
||||
// Check if user's tenant owns the knowledge base
|
||||
if kb.TenantID != tenantID {
|
||||
return nil, ErrNotKBOwner
|
||||
}
|
||||
|
||||
// Verify organization exists
|
||||
_, err = s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user is a member of the organization and has at least editor role (viewers cannot share KBs to the org)
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !member.Role.HasPermission(types.OrgRoleEditor) {
|
||||
return nil, ErrOrgRoleCannotShare
|
||||
}
|
||||
|
||||
if !permission.IsValid() {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
|
||||
share := &types.KnowledgeBaseShare{
|
||||
ID: uuid.New().String(),
|
||||
KnowledgeBaseID: kbID,
|
||||
OrganizationID: orgID,
|
||||
SharedByUserID: userID,
|
||||
SourceTenantID: tenantID,
|
||||
Permission: permission,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.shareRepo.Create(ctx, share); err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareAlreadyExists) {
|
||||
// Update existing share
|
||||
existingShare, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existingShare.Permission = permission
|
||||
existingShare.UpdatedAt = time.Now()
|
||||
if err := s.shareRepo.Update(ctx, existingShare); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return existingShare, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base %s shared successfully to organization %s", kbID, orgID)
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// UpdateSharePermission updates the permission of a share
|
||||
func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return ErrShareNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Only the user who shared can update
|
||||
if share.SharedByUserID != userID {
|
||||
return ErrSharePermissionDenied
|
||||
}
|
||||
|
||||
if !permission.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
share.Permission = permission
|
||||
share.UpdatedAt = time.Now()
|
||||
|
||||
return s.shareRepo.Update(ctx, share)
|
||||
}
|
||||
|
||||
// RemoveShare removes a share.
|
||||
// Allowed if: (1) current user is the sharer, or (2) current user is admin of the target organization.
|
||||
// Org admins can unlink any KB shared to their org (e.g. content governance, sharer left).
|
||||
func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string) error {
|
||||
share, err := s.shareRepo.GetByID(ctx, shareID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return ErrShareNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Sharer can always remove their own share
|
||||
if share.SharedByUserID == userID {
|
||||
return s.shareRepo.Delete(ctx, shareID)
|
||||
}
|
||||
|
||||
// Org admin can remove any share targeting their organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err == nil && member.Role == types.OrgRoleAdmin {
|
||||
return s.shareRepo.Delete(ctx, shareID)
|
||||
}
|
||||
|
||||
return ErrSharePermissionDenied
|
||||
}
|
||||
|
||||
// ListSharesByKnowledgeBase lists all shares for a knowledge base
|
||||
func (s *kbShareService) ListSharesByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
return s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
}
|
||||
|
||||
// ListSharesByOrganization lists all shares for an organization
|
||||
func (s *kbShareService) ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error) {
|
||||
return s.shareRepo.ListByOrganization(ctx, orgID)
|
||||
}
|
||||
|
||||
// ListSharedKnowledgeBases lists all knowledge bases shared to the user through organizations
|
||||
// It filters out knowledge bases that belong to the user's own tenant
|
||||
// It deduplicates knowledge bases that are shared to multiple organizations the user belongs to
|
||||
func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error) {
|
||||
shares, err := s.shareRepo.ListSharedKBsForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use a map to deduplicate by knowledge base ID, keeping the one with highest permission
|
||||
kbInfoMap := make(map[string]*types.SharedKnowledgeBaseInfo)
|
||||
|
||||
for _, share := range shares {
|
||||
// Skip knowledge bases that belong to the user's own tenant
|
||||
// (user already has full ownership of these)
|
||||
if share.SourceTenantID == currentTenantID {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip if knowledge base is nil
|
||||
if share.KnowledgeBase == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
kbID := share.KnowledgeBase.ID
|
||||
|
||||
// Get user's role in the organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err != nil {
|
||||
continue // Skip if user is not a member anymore
|
||||
}
|
||||
|
||||
// Effective permission is the lower of share permission and user's org role
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
kb := share.KnowledgeBase
|
||||
// Calculate knowledge/chunk count based on type
|
||||
switch kb.Type {
|
||||
case types.KnowledgeBaseTypeDocument:
|
||||
knowledgeCount, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge count for shared KB %s: %v", kb.ID, err)
|
||||
} else {
|
||||
kb.KnowledgeCount = knowledgeCount
|
||||
}
|
||||
case types.KnowledgeBaseTypeFAQ:
|
||||
chunkCount, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get chunk count for shared KB %s: %v", kb.ID, err)
|
||||
} else {
|
||||
kb.ChunkCount = chunkCount
|
||||
}
|
||||
}
|
||||
|
||||
info := &types.SharedKnowledgeBaseInfo{
|
||||
KnowledgeBase: kb,
|
||||
ShareID: share.ID,
|
||||
OrganizationID: share.OrganizationID,
|
||||
OrgName: "",
|
||||
Permission: effectivePermission,
|
||||
SourceTenantID: share.SourceTenantID,
|
||||
SharedAt: share.CreatedAt,
|
||||
}
|
||||
|
||||
if share.Organization != nil {
|
||||
info.OrgName = share.Organization.Name
|
||||
}
|
||||
|
||||
// Check if we already have this knowledge base
|
||||
existing, exists := kbInfoMap[kbID]
|
||||
if !exists {
|
||||
// First time seeing this KB, add it
|
||||
kbInfoMap[kbID] = info
|
||||
} else {
|
||||
// KB already exists, keep the one with higher permission
|
||||
// Permission hierarchy: admin(3) > editor(2) > viewer(1)
|
||||
// If current permission is higher than existing, replace
|
||||
// This handles the case where a user belongs to multiple orgs with different permissions
|
||||
if effectivePermission.HasPermission(existing.Permission) && effectivePermission != existing.Permission {
|
||||
// Current permission is higher, replace with higher permission
|
||||
kbInfoMap[kbID] = info
|
||||
}
|
||||
// If existing permission is higher or equal, keep existing (no change needed)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to slice
|
||||
result := make([]*types.SharedKnowledgeBaseInfo, 0, len(kbInfoMap))
|
||||
for _, info := range kbInfoMap {
|
||||
result = append(result, info)
|
||||
}
|
||||
|
||||
return result, 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)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return nil, ErrShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// GetShareByKBAndOrg gets a share by knowledge base and organization
|
||||
func (s *kbShareService) GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error) {
|
||||
share, err := s.shareRepo.GetByKBAndOrg(ctx, kbID, orgID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrKBShareNotFound) {
|
||||
return nil, ErrShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return share, nil
|
||||
}
|
||||
|
||||
// CheckUserKBPermission checks a user's permission for a knowledge base
|
||||
// Returns: permission level, isShared, error
|
||||
func (s *kbShareService) CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error) {
|
||||
// Get all shares for this knowledge base
|
||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
var highestPermission types.OrgMemberRole
|
||||
isShared := false
|
||||
|
||||
for _, share := range shares {
|
||||
// Check if user is a member of the organization
|
||||
member, err := s.orgRepo.GetMember(ctx, share.OrganizationID, userID)
|
||||
if err != nil {
|
||||
continue // User is not a member of this org
|
||||
}
|
||||
|
||||
isShared = true
|
||||
|
||||
// Effective permission is the lower of share permission and user's org role
|
||||
effectivePermission := share.Permission
|
||||
if !member.Role.HasPermission(share.Permission) {
|
||||
effectivePermission = member.Role
|
||||
}
|
||||
|
||||
// Keep the highest permission
|
||||
if highestPermission == "" || effectivePermission.HasPermission(highestPermission) {
|
||||
highestPermission = effectivePermission
|
||||
}
|
||||
}
|
||||
|
||||
return highestPermission, isShared, nil
|
||||
}
|
||||
|
||||
// HasKBPermission checks if a user has at least the required permission level for a knowledge base
|
||||
func (s *kbShareService) HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error) {
|
||||
permission, isShared, err := s.CheckUserKBPermission(ctx, kbID, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if !isShared {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return permission.HasPermission(requiredRole), nil
|
||||
}
|
||||
|
||||
// GetKBSourceTenant gets the source tenant ID for a shared knowledge base
|
||||
func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error) {
|
||||
// First check if there are any shares for this KB
|
||||
shares, err := s.shareRepo.ListByKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if len(shares) > 0 {
|
||||
return shares[0].SourceTenantID, nil
|
||||
}
|
||||
|
||||
// If not shared, get the tenant from the knowledge base itself
|
||||
kb, err := s.kbRepo.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return 0, ErrKBNotFound
|
||||
}
|
||||
|
||||
return kb.TenantID, nil
|
||||
}
|
||||
|
||||
// CountSharesByKnowledgeBaseIDs counts the number of shares for multiple knowledge bases
|
||||
func (s *kbShareService) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
|
||||
return s.shareRepo.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
|
||||
}
|
||||
|
|
@ -70,6 +70,7 @@ type knowledgeService struct {
|
|||
task *asynq.Client
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
redisClient *redis.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
const (
|
||||
|
|
@ -95,6 +96,7 @@ func NewKnowledgeService(
|
|||
graphEngine interfaces.RetrieveGraphRepository,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
redisClient *redis.Client,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) (interfaces.KnowledgeService, error) {
|
||||
return &knowledgeService{
|
||||
config: config,
|
||||
|
|
@ -112,6 +114,7 @@ func NewKnowledgeService(
|
|||
graphEngine: graphEngine,
|
||||
retrieveEngine: retrieveEngine,
|
||||
redisClient: redisClient,
|
||||
kbShareService: kbShareService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -713,6 +716,11 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty
|
|||
return knowledge, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeByIDOnly retrieves knowledge by ID without tenant filter (for permission resolution).
|
||||
func (s *knowledgeService) GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) {
|
||||
return s.repo.GetKnowledgeByIDOnly(ctx, id)
|
||||
}
|
||||
|
||||
// ListKnowledgeByKnowledgeBaseID returns all knowledge entries in a knowledge base
|
||||
func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
|
||||
kbID string,
|
||||
|
|
@ -2229,6 +2237,50 @@ func (s *knowledgeService) GetKnowledgeBatch(ctx context.Context,
|
|||
return s.repo.GetKnowledgeBatch(ctx, tenantID, ids)
|
||||
}
|
||||
|
||||
// GetKnowledgeBatchWithSharedAccess retrieves knowledge by IDs, including items from shared KBs the user has access to.
|
||||
// Used when building search targets so that @mentioned files from shared KBs are included.
|
||||
func (s *knowledgeService) GetKnowledgeBatchWithSharedAccess(ctx context.Context,
|
||||
tenantID uint64, ids []string,
|
||||
) ([]*types.Knowledge, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
ownList, err := s.repo.GetKnowledgeBatch(ctx, tenantID, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
foundSet := make(map[string]bool)
|
||||
for _, k := range ownList {
|
||||
if k != nil {
|
||||
foundSet[k.ID] = true
|
||||
}
|
||||
}
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return ownList, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
return ownList, nil
|
||||
}
|
||||
for _, id := range ids {
|
||||
if foundSet[id] {
|
||||
continue
|
||||
}
|
||||
k, err := s.repo.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
continue
|
||||
}
|
||||
foundSet[k.ID] = true
|
||||
ownList = append(ownList, k)
|
||||
}
|
||||
return ownList, nil
|
||||
}
|
||||
|
||||
// calculateFileHash calculates MD5 hash of a file
|
||||
func calculateFileHash(file *multipart.FileHeader) (string, error) {
|
||||
f, err := file.Open()
|
||||
|
|
@ -2677,8 +2729,35 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if this is a shared knowledge base access
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
effectiveTenantID := tenantID
|
||||
|
||||
// If the kb belongs to a different tenant, check for shared access
|
||||
if kb.TenantID != tenantID {
|
||||
// Get user ID from context
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
userID := userIDVal.(string)
|
||||
|
||||
// Check if user has at least viewer permission through organization sharing
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
|
||||
// Use the source tenant ID for data access
|
||||
sourceTenantID, err := s.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
effectiveTenantID = sourceTenantID
|
||||
}
|
||||
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, effectiveTenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -2689,7 +2768,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
// Convert tagSeqID to tagID (UUID)
|
||||
var tagID string
|
||||
if tagSeqID > 0 {
|
||||
tag, err := s.tagRepo.GetBySeqID(ctx, tenantID, tagSeqID)
|
||||
tag, err := s.tagRepo.GetBySeqID(ctx, effectiveTenantID, tagSeqID)
|
||||
if err != nil {
|
||||
return nil, werrors.NewNotFoundError("标签不存在")
|
||||
}
|
||||
|
|
@ -2698,7 +2777,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
|
||||
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
|
||||
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
|
||||
ctx, tenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
|
||||
ctx, effectiveTenantID, faqKnowledge.ID, page, chunkType, tagID, keyword, searchField, sortOrder, types.KnowledgeTypeFAQ,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -2718,7 +2797,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
}
|
||||
}
|
||||
if len(tagIDs) > 0 {
|
||||
tags, err := s.tagRepo.GetByIDs(ctx, tenantID, tagIDs)
|
||||
tags, err := s.tagRepo.GetByIDs(ctx, effectiveTenantID, tagIDs)
|
||||
if err == nil {
|
||||
for _, tag := range tags {
|
||||
tagNameMap[tag.ID] = tag.Name
|
||||
|
|
@ -4562,7 +4641,14 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates
|
|||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tenantIDVal := ctx.Value(types.TenantIDContextKey)
|
||||
if tenantIDVal == nil {
|
||||
return werrors.NewUnauthorizedError("tenant ID not found in context")
|
||||
}
|
||||
tenantID, ok := tenantIDVal.(uint64)
|
||||
if !ok {
|
||||
return werrors.NewUnauthorizedError("invalid tenant ID in context")
|
||||
}
|
||||
|
||||
// Get all knowledge items in batch
|
||||
knowledgeIDs := make([]string, 0, len(updates))
|
||||
|
|
@ -7456,14 +7542,47 @@ func (s *knowledgeService) getOrCreateTagInTarget(
|
|||
return newTag.ID
|
||||
}
|
||||
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant and shared knowledge bases.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, false, werrors.NewUnauthorizedError("Tenant ID not found in context")
|
||||
}
|
||||
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit, fileTypes)
|
||||
|
||||
scopes := make([]types.KnowledgeSearchScope, 0)
|
||||
|
||||
// Own tenant: document-type knowledge bases
|
||||
ownKBs, err := s.kbService.ListKnowledgeBases(ctx)
|
||||
if err == nil {
|
||||
for _, kb := range ownKBs {
|
||||
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: tenantID, KBID: kb.ID})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared knowledge bases (document type only)
|
||||
if userIDVal := ctx.Value(types.UserIDContextKey); userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err == nil {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && info.KnowledgeBase.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{
|
||||
TenantID: info.SourceTenantID,
|
||||
KBID: info.KnowledgeBase.ID,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
}
|
||||
|
||||
// ProcessKnowledgeListDelete handles Asynq knowledge list delete tasks
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ type knowledgeBaseService struct {
|
|||
repo interfaces.KnowledgeBaseRepository
|
||||
kgRepo interfaces.KnowledgeRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
shareRepo interfaces.KBShareRepository
|
||||
kbShareService interfaces.KBShareService
|
||||
modelService interfaces.ModelService
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
tenantRepo interfaces.TenantRepository
|
||||
|
|
@ -37,6 +39,8 @@ type knowledgeBaseService struct {
|
|||
func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
||||
kgRepo interfaces.KnowledgeRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
shareRepo interfaces.KBShareRepository,
|
||||
kbShareService interfaces.KBShareService,
|
||||
modelService interfaces.ModelService,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
|
|
@ -48,6 +52,8 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
|||
repo: repo,
|
||||
kgRepo: kgRepo,
|
||||
chunkRepo: chunkRepo,
|
||||
shareRepo: shareRepo,
|
||||
kbShareService: kbShareService,
|
||||
modelService: modelService,
|
||||
retrieveEngine: retrieveEngine,
|
||||
tenantRepo: tenantRepo,
|
||||
|
|
@ -113,6 +119,26 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri
|
|||
return kb, nil
|
||||
}
|
||||
|
||||
// GetKnowledgeBaseByIDOnly retrieves knowledge base by ID without tenant filter
|
||||
// Used for cross-tenant shared KB access where permission is checked elsewhere
|
||||
func (s *knowledgeBaseService) GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, errors.New("knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBases returns all knowledge bases for a tenant
|
||||
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
|
@ -241,6 +267,11 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
|
|||
return err
|
||||
}
|
||||
|
||||
// Step 1b: Remove all organization shares for this KB so org settings no longer show them
|
||||
if delErr := s.shareRepo.DeleteByKnowledgeBaseID(ctx, id); delErr != nil {
|
||||
logger.Warnf(ctx, "Failed to delete KB shares for knowledge base %s: %v", id, delErr)
|
||||
}
|
||||
|
||||
// Step 2: Enqueue async task for heavy cleanup operations
|
||||
payload := types.KBDeletePayload{
|
||||
TenantID: tenantID,
|
||||
|
|
@ -493,6 +524,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
|||
logger.Infof(ctx, "Hybrid search parameters, knowledge base ID: %s, query text: %s", id, params.QueryText)
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
currentTenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
// Create a composite retrieval engine with tenant's configured retrievers
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
|
|
@ -520,7 +552,16 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
|||
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
|
||||
|
||||
logger.Infof(ctx, "Getting embedding model, model ID: %s", kb.EmbeddingModelID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
|
||||
// Check if this is a cross-tenant shared knowledge base
|
||||
// For shared KB, we must use the source tenant's embedding model to ensure vector compatibility
|
||||
if kb.TenantID != currentTenantID {
|
||||
logger.Infof(ctx, "Cross-tenant knowledge base detected, using source tenant's embedding model. KB tenant: %d, current tenant: %d", kb.TenantID, currentTenantID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModelForTenant(ctx, kb.EmbeddingModelID, kb.TenantID)
|
||||
} else {
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get embedding model, model ID: %s, error: %v", kb.EmbeddingModelID, err)
|
||||
return nil, err
|
||||
|
|
@ -1016,16 +1057,16 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
|||
chunkMatchedContents[chunk.ChunkID] = chunk.Content
|
||||
}
|
||||
|
||||
// Batch fetch knowledge data
|
||||
// Batch fetch knowledge data (include shared KB so cross-tenant retrieval works)
|
||||
logger.Infof(ctx, "Fetching knowledge data for %d IDs", len(knowledgeIDs))
|
||||
knowledgeMap, err := s.fetchKnowledgeData(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeMap, err := s.fetchKnowledgeDataWithShared(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Batch fetch all chunks in one go
|
||||
// Batch fetch chunks (include shared KB chunks: first by tenant, then by ID-only for missing with permission check)
|
||||
logger.Infof(ctx, "Fetching chunk data for %d IDs", len(chunkIDs))
|
||||
allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
allChunks, err := s.listChunksByIDWithShared(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
|
|
@ -1077,10 +1118,10 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
|||
}
|
||||
}
|
||||
|
||||
// Fetch all additional chunks in one go if needed
|
||||
// Fetch all additional chunks in one go if needed (include shared KB)
|
||||
if len(additionalChunkIDs) > 0 {
|
||||
logger.Infof(ctx, "Fetching %d additional chunks", len(additionalChunkIDs))
|
||||
additionalChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, additionalChunkIDs)
|
||||
additionalChunks, err := s.listChunksByIDWithShared(ctx, tenantID, additionalChunkIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch some additional chunks: %v", err)
|
||||
// Continue with what we have
|
||||
|
|
@ -1226,3 +1267,136 @@ func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context,
|
|||
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// fetchKnowledgeDataWithShared gets knowledge data in batch, including knowledge from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeIDs []string,
|
||||
) (map[string]*types.Knowledge, error) {
|
||||
knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"knowledge_ids": knowledgeIDs,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
knowledgeMap := make(map[string]*types.Knowledge, len(knowledges))
|
||||
for _, k := range knowledges {
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
|
||||
// Count how many IDs are missing (not found in current tenant)
|
||||
var missingIDs []string
|
||||
for _, id := range knowledgeIDs {
|
||||
if knowledgeMap[id] == nil {
|
||||
missingIDs = append(missingIDs, id)
|
||||
}
|
||||
}
|
||||
if len(missingIDs) == 0 {
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] %d knowledge IDs not found in current tenant, attempting shared KB lookup", len(missingIDs))
|
||||
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
logger.Warnf(ctx, "[fetchKnowledgeDataWithShared] userID not found in context, skipping shared KB lookup")
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
logger.Warnf(ctx, "[fetchKnowledgeDataWithShared] userID is empty, skipping shared KB lookup")
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID)
|
||||
for _, id := range missingIDs {
|
||||
k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id)
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] No permission for KB %s", k.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Found shared knowledge %s in KB %s", id, k.KnowledgeBaseID)
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] After shared lookup, total knowledge found: %d", len(knowledgeMap))
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// listChunksByIDWithShared fetches chunks by IDs, including chunks from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkIDs []string,
|
||||
) ([]*types.Chunk, error) {
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
foundSet := make(map[string]bool)
|
||||
for _, c := range chunks {
|
||||
if c != nil {
|
||||
foundSet[c.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
var missing []string
|
||||
for _, id := range chunkIDs {
|
||||
if !foundSet[id] {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] %d chunks not found in current tenant, attempting shared KB lookup", len(missing))
|
||||
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] userID not found in context, skipping shared KB lookup")
|
||||
return chunks, nil
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] userID is empty, skipping shared KB lookup")
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID)
|
||||
crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err)
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Found %d chunks without tenant filter", len(crossChunks))
|
||||
|
||||
for _, c := range crossChunks {
|
||||
if c == nil || c.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, c.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] No permission for KB %s", c.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
chunks = append(chunks, c)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] After shared lookup, total chunks: %d", len(chunks))
|
||||
return chunks, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -268,6 +268,62 @@ func (s *modelService) GetEmbeddingModel(ctx context.Context, modelId string) (e
|
|||
return embedder, nil
|
||||
}
|
||||
|
||||
// GetEmbeddingModelForTenant retrieves and initializes an embedding model for a specific tenant
|
||||
// This is used for cross-tenant knowledge base sharing where the embedding model from
|
||||
// the source tenant must be used to ensure vector compatibility
|
||||
func (s *modelService) GetEmbeddingModelForTenant(ctx context.Context, modelId string, tenantID uint64) (embedding.Embedder, error) {
|
||||
// Check if model ID is empty
|
||||
if modelId == "" {
|
||||
logger.Error(ctx, "Model ID is empty")
|
||||
return nil, errors.New("model ID cannot be empty")
|
||||
}
|
||||
|
||||
// Fetch model from repository using the specified tenant ID
|
||||
model, err := s.repo.GetByID(ctx, tenantID, modelId)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": modelId,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if model == nil {
|
||||
logger.Error(ctx, "Model not found for specified tenant")
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
|
||||
if model.Status != types.ModelStatusActive {
|
||||
logger.Errorf(ctx, "Model is not active, status: %s", model.Status)
|
||||
return nil, errors.New("model is not active")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting cross-tenant embedding model: %s, source: %s, tenant: %d", model.Name, model.Source, tenantID)
|
||||
|
||||
// Initialize the embedder with model configuration
|
||||
embedder, err := embedding.NewEmbedder(embedding.Config{
|
||||
Source: model.Source,
|
||||
BaseURL: model.Parameters.BaseURL,
|
||||
APIKey: model.Parameters.APIKey,
|
||||
ModelID: model.ID,
|
||||
ModelName: model.Name,
|
||||
Dimensions: model.Parameters.EmbeddingParameters.Dimension,
|
||||
TruncatePromptTokens: model.Parameters.EmbeddingParameters.TruncatePromptTokens,
|
||||
Provider: model.Parameters.Provider,
|
||||
}, s.pooler, s.ollamaService)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"model_id": model.ID,
|
||||
"model_name": model.Name,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Cross-tenant embedding model initialized successfully")
|
||||
return embedder, nil
|
||||
}
|
||||
|
||||
// GetRerankModel retrieves and initializes a reranking model instance
|
||||
// Takes a model ID and returns a Reranker interface implementation
|
||||
func (s *modelService) GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,587 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Default invite code validity in days; allowed values: 0 (never), 1, 7, 30
|
||||
const DefaultInviteCodeValidityDays = 7
|
||||
|
||||
// ValidInviteCodeValidityDays are the allowed values for invite_code_validity_days
|
||||
var ValidInviteCodeValidityDays = map[int]bool{0: true, 1: true, 7: true, 30: true}
|
||||
|
||||
var (
|
||||
ErrOrgNotFound = errors.New("organization not found")
|
||||
ErrOrgPermissionDenied = errors.New("permission denied for this organization")
|
||||
ErrCannotRemoveOwner = errors.New("cannot remove organization owner")
|
||||
ErrCannotChangeOwnerRole = errors.New("cannot change organization owner role")
|
||||
ErrUserNotInOrg = errors.New("user is not a member of this organization")
|
||||
ErrInvalidRole = errors.New("invalid role")
|
||||
ErrInviteCodeExpired = errors.New("invite code has expired")
|
||||
ErrInvalidValidityDays = errors.New("invite_code_validity_days must be 0, 1, 7, or 30")
|
||||
)
|
||||
|
||||
// organizationService implements OrganizationService interface
|
||||
type organizationService struct {
|
||||
orgRepo interfaces.OrganizationRepository
|
||||
userRepo interfaces.UserRepository
|
||||
shareRepo interfaces.KBShareRepository
|
||||
}
|
||||
|
||||
// NewOrganizationService creates a new organization service
|
||||
func NewOrganizationService(orgRepo interfaces.OrganizationRepository, userRepo interfaces.UserRepository, shareRepo interfaces.KBShareRepository) interfaces.OrganizationService {
|
||||
return &organizationService{
|
||||
orgRepo: orgRepo,
|
||||
userRepo: userRepo,
|
||||
shareRepo: shareRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// resolveInviteExpiry returns expiresAt for the given validity days (0 = never, nil expiresAt).
|
||||
func resolveInviteExpiry(validityDays int, now time.Time) *time.Time {
|
||||
if validityDays == 0 {
|
||||
return nil
|
||||
}
|
||||
t := now.AddDate(0, 0, validityDays)
|
||||
return &t
|
||||
}
|
||||
|
||||
// CreateOrganization creates a new organization
|
||||
func (s *organizationService) CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error) {
|
||||
logger.Infof(ctx, "Creating organization: %s by user: %s", req.Name, userID)
|
||||
|
||||
validityDays := DefaultInviteCodeValidityDays
|
||||
if req.InviteCodeValidityDays != nil {
|
||||
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
||||
return nil, ErrInvalidValidityDays
|
||||
}
|
||||
validityDays = *req.InviteCodeValidityDays
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
org := &types.Organization{
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: strings.TrimSpace(req.Avatar),
|
||||
OwnerID: userID,
|
||||
InviteCode: generateInviteCode(),
|
||||
InviteCodeExpiresAt: resolveInviteExpiry(validityDays, now),
|
||||
InviteCodeValidityDays: validityDays,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := s.orgRepo.Create(ctx, org); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create organization: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add the creator as admin member
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: org.ID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: types.OrgRoleAdmin,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
logger.Errorf(ctx, "Failed to add creator as member: %v", err)
|
||||
// Rollback organization creation
|
||||
_ = s.orgRepo.Delete(ctx, org.ID)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Organization created successfully: %s", org.ID)
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// GetOrganization gets an organization by ID
|
||||
func (s *organizationService) GetOrganization(ctx context.Context, id string) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrganizationNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// GetOrganizationByInviteCode gets an organization by invite code
|
||||
func (s *organizationService) GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrInviteCodeNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
if errors.Is(err, repository.ErrInviteCodeExpired) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// ListUserOrganizations lists all organizations that a user belongs to
|
||||
func (s *organizationService) ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error) {
|
||||
return s.orgRepo.ListByUserID(ctx, userID)
|
||||
}
|
||||
|
||||
// UpdateOrganization updates an organization
|
||||
func (s *organizationService) UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error) {
|
||||
// Check if user is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, id, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isAdmin {
|
||||
return nil, ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
org, err := s.orgRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
org.Name = *req.Name
|
||||
}
|
||||
if req.Description != nil {
|
||||
org.Description = *req.Description
|
||||
}
|
||||
if req.Avatar != nil {
|
||||
org.Avatar = strings.TrimSpace(*req.Avatar)
|
||||
}
|
||||
if req.RequireApproval != nil {
|
||||
org.RequireApproval = *req.RequireApproval
|
||||
}
|
||||
if req.InviteCodeValidityDays != nil {
|
||||
if !ValidInviteCodeValidityDays[*req.InviteCodeValidityDays] {
|
||||
return nil, ErrInvalidValidityDays
|
||||
}
|
||||
org.InviteCodeValidityDays = *req.InviteCodeValidityDays
|
||||
}
|
||||
org.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.orgRepo.Update(ctx, org); 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)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Only owner can delete organization
|
||||
if org.OwnerID != userID {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
// Remove all KB shares for this org so members no longer see associated knowledge bases
|
||||
if err := s.shareRepo.DeleteByOrganizationID(ctx, id); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete KB shares for organization %s: %v", id, err)
|
||||
}
|
||||
|
||||
return s.orgRepo.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// AddMember adds a member to an organization
|
||||
func (s *organizationService) AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error {
|
||||
if !role.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: role,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
return s.orgRepo.AddMember(ctx, member)
|
||||
}
|
||||
|
||||
// RemoveMember removes a member from an organization.
|
||||
// When operatorUserID == memberUserID, it is "leave" (self-removal) and does not require admin.
|
||||
// When removing another member, operator must be admin.
|
||||
func (s *organizationService) RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error {
|
||||
// Check if trying to remove owner
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if org.OwnerID == memberUserID {
|
||||
return ErrCannotRemoveOwner
|
||||
}
|
||||
|
||||
// Self-removal (leave): allow any member to leave
|
||||
if operatorUserID == memberUserID {
|
||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
||||
}
|
||||
|
||||
// Removing another member: require operator to be admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isAdmin {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
return s.orgRepo.RemoveMember(ctx, orgID, memberUserID)
|
||||
}
|
||||
|
||||
// UpdateMemberRole updates a member's role
|
||||
func (s *organizationService) UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error {
|
||||
if !role.IsValid() {
|
||||
return ErrInvalidRole
|
||||
}
|
||||
|
||||
// Check if operator is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, operatorUserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isAdmin {
|
||||
return ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
// Check if trying to change owner's role
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if org.OwnerID == memberUserID {
|
||||
return ErrCannotChangeOwnerRole
|
||||
}
|
||||
|
||||
return s.orgRepo.UpdateMemberRole(ctx, orgID, memberUserID, role)
|
||||
}
|
||||
|
||||
// ListMembers lists all members of an organization
|
||||
func (s *organizationService) ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error) {
|
||||
return s.orgRepo.ListMembers(ctx, orgID)
|
||||
}
|
||||
|
||||
// GetMember gets a specific member of an organization
|
||||
func (s *organizationService) GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// GenerateInviteCode generates a new invite code for an organization
|
||||
func (s *organizationService) GenerateInviteCode(ctx context.Context, orgID string, userID string) (string, error) {
|
||||
// Check if user is admin
|
||||
isAdmin, err := s.IsOrgAdmin(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !isAdmin {
|
||||
return "", ErrOrgPermissionDenied
|
||||
}
|
||||
|
||||
org, err := s.orgRepo.GetByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
validityDays := org.InviteCodeValidityDays
|
||||
if validityDays != 0 && !ValidInviteCodeValidityDays[validityDays] {
|
||||
validityDays = DefaultInviteCodeValidityDays
|
||||
}
|
||||
// 0 = never expire (expiresAt nil); 1/7/30 = that many days
|
||||
|
||||
inviteCode := generateInviteCode()
|
||||
now := time.Now()
|
||||
expiresAt := resolveInviteExpiry(validityDays, now)
|
||||
if err := s.orgRepo.UpdateInviteCode(ctx, orgID, inviteCode, expiresAt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return inviteCode, nil
|
||||
}
|
||||
|
||||
// JoinByInviteCode allows a user to join an organization via invite code
|
||||
func (s *organizationService) JoinByInviteCode(ctx context.Context, inviteCode string, userID string, tenantID uint64) (*types.Organization, error) {
|
||||
org, err := s.orgRepo.GetByInviteCode(ctx, inviteCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrInviteCodeNotFound) {
|
||||
return nil, ErrOrgNotFound
|
||||
}
|
||||
if errors.Is(err, repository.ErrInviteCodeExpired) {
|
||||
return nil, ErrInviteCodeExpired
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user is already a member
|
||||
_, err = s.orgRepo.GetMember(ctx, org.ID, userID)
|
||||
if err == nil {
|
||||
// User is already a member, just return the organization
|
||||
return org, nil
|
||||
}
|
||||
if !errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add user as viewer by default
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: org.ID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
Role: types.OrgRoleViewer,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "User %s joined organization %s via invite code", userID, org.ID)
|
||||
return org, nil
|
||||
}
|
||||
|
||||
// IsOrgAdmin checks if a user is an admin of an organization
|
||||
func (s *organizationService) IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return member.Role == types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
// GetUserRoleInOrg gets a user's role in an organization
|
||||
func (s *organizationService) GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error) {
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return "", ErrUserNotInOrg
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return member.Role, nil
|
||||
}
|
||||
|
||||
// generateInviteCode generates a random 16-character invite code
|
||||
func generateInviteCode() string {
|
||||
bytes := make([]byte, 8)
|
||||
_, _ = rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// ----------------
|
||||
// Join Requests
|
||||
// ----------------
|
||||
|
||||
var (
|
||||
ErrPendingRequestExists = errors.New("pending request already exists")
|
||||
ErrJoinRequestNotFound = errors.New("join request not found")
|
||||
ErrCannotUpgradeToSameRole = errors.New("cannot request upgrade to same or lower role")
|
||||
ErrAlreadyAdmin = errors.New("user is already an admin")
|
||||
)
|
||||
|
||||
// SubmitJoinRequest submits a request to join an organization
|
||||
func (s *organizationService) SubmitJoinRequest(ctx context.Context, orgID string, userID string, tenantID uint64, message string, requestedRole types.OrgMemberRole) (*types.OrganizationJoinRequest, error) {
|
||||
logger.Infof(ctx, "User %s submitting join request for organization %s", userID, orgID)
|
||||
|
||||
// Check if there's already a pending join request
|
||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeJoin)
|
||||
if err == nil && existing != nil {
|
||||
return nil, ErrPendingRequestExists
|
||||
}
|
||||
|
||||
// Default to viewer if role is empty or invalid
|
||||
if requestedRole == "" || !requestedRole.IsValid() {
|
||||
requestedRole = types.OrgRoleViewer
|
||||
}
|
||||
|
||||
request := &types.OrganizationJoinRequest{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
RequestType: types.JoinRequestTypeJoin,
|
||||
RequestedRole: requestedRole,
|
||||
Status: types.JoinRequestStatusPending,
|
||||
Message: message,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.CreateJoinRequest(ctx, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Join request %s created for organization %s by user %s", request.ID, orgID, userID)
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// ListJoinRequests lists all join requests for an organization
|
||||
func (s *organizationService) ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error) {
|
||||
return s.orgRepo.ListJoinRequests(ctx, orgID, "")
|
||||
}
|
||||
|
||||
// CountPendingJoinRequests returns the number of pending join requests for an organization
|
||||
func (s *organizationService) CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error) {
|
||||
return s.orgRepo.CountJoinRequests(ctx, orgID, types.JoinRequestStatusPending)
|
||||
}
|
||||
|
||||
// ReviewJoinRequest reviews a join request or upgrade request (approve or reject).
|
||||
// When approving, assignRole overrides the applicant's requested role if set; otherwise uses request.RequestedRole or viewer.
|
||||
func (s *organizationService) ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error {
|
||||
request, err := s.orgRepo.GetJoinRequestByID(ctx, requestID)
|
||||
if err != nil {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
if request.OrganizationID != orgID {
|
||||
return ErrJoinRequestNotFound
|
||||
}
|
||||
|
||||
if request.Status != types.JoinRequestStatusPending {
|
||||
return errors.New("request has already been reviewed")
|
||||
}
|
||||
|
||||
var status types.JoinRequestStatus
|
||||
if approved {
|
||||
status = types.JoinRequestStatusApproved
|
||||
|
||||
// Role to assign: admin override > applicant's requested role > viewer
|
||||
role := types.OrgRoleViewer
|
||||
if assignRole != nil && assignRole.IsValid() {
|
||||
role = *assignRole
|
||||
} else if request.RequestedRole != "" && request.RequestedRole.IsValid() {
|
||||
role = request.RequestedRole
|
||||
}
|
||||
|
||||
// Handle based on request type
|
||||
if request.RequestType == types.JoinRequestTypeUpgrade {
|
||||
// Upgrade: update existing member's role
|
||||
if err := s.orgRepo.UpdateMemberRole(ctx, request.OrganizationID, request.UserID, role); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Upgrade request %s approved, user %s role updated to %s in organization %s", requestID, request.UserID, role, request.OrganizationID)
|
||||
} else {
|
||||
// Join: add new member
|
||||
member := &types.OrganizationMember{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: request.OrganizationID,
|
||||
UserID: request.UserID,
|
||||
TenantID: request.TenantID,
|
||||
Role: role,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := s.orgRepo.AddMember(ctx, member); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(ctx, "Join request %s approved, user %s added to organization %s with role %s", requestID, request.UserID, request.OrganizationID, role)
|
||||
}
|
||||
} else {
|
||||
status = types.JoinRequestStatusRejected
|
||||
logger.Infof(ctx, "Request %s rejected for user %s", requestID, request.UserID)
|
||||
}
|
||||
|
||||
return s.orgRepo.UpdateJoinRequestStatus(ctx, requestID, status, reviewerID, message)
|
||||
}
|
||||
|
||||
// RequestRoleUpgrade submits a request to upgrade role in an organization
|
||||
func (s *organizationService) RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error) {
|
||||
logger.Infof(ctx, "User %s submitting role upgrade request for organization %s to role %s", userID, orgID, requestedRole)
|
||||
|
||||
// Check if user is a member
|
||||
member, err := s.orgRepo.GetMember(ctx, orgID, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrOrgMemberNotFound) {
|
||||
return nil, ErrUserNotInOrg
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate the requested role
|
||||
if !requestedRole.IsValid() {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
|
||||
// Check if already admin
|
||||
if member.Role == types.OrgRoleAdmin {
|
||||
return nil, ErrAlreadyAdmin
|
||||
}
|
||||
|
||||
// Check if requested role is higher than current role
|
||||
if !requestedRole.HasPermission(member.Role) || requestedRole == member.Role {
|
||||
return nil, ErrCannotUpgradeToSameRole
|
||||
}
|
||||
|
||||
// Check if there's already a pending upgrade request
|
||||
existing, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
||||
if err == nil && existing != nil {
|
||||
return nil, ErrPendingRequestExists
|
||||
}
|
||||
|
||||
request := &types.OrganizationJoinRequest{
|
||||
ID: uuid.New().String(),
|
||||
OrganizationID: orgID,
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
RequestType: types.JoinRequestTypeUpgrade,
|
||||
PrevRole: member.Role,
|
||||
RequestedRole: requestedRole,
|
||||
Status: types.JoinRequestStatusPending,
|
||||
Message: message,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.orgRepo.CreateJoinRequest(ctx, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Role upgrade request %s created for organization %s by user %s (from %s to %s)", request.ID, orgID, userID, member.Role, requestedRole)
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// GetPendingUpgradeRequest gets a pending upgrade request for a user in an organization
|
||||
func (s *organizationService) GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error) {
|
||||
request, err := s.orgRepo.GetPendingRequestByType(ctx, orgID, userID, types.JoinRequestTypeUpgrade)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrJoinRequestNotFound) {
|
||||
return nil, ErrJoinRequestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
|
|
@ -43,6 +43,7 @@ type sessionService struct {
|
|||
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
|
||||
chunkService interfaces.ChunkService // Service for chunk operations
|
||||
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
}
|
||||
|
||||
// NewSessionService creates a new session service instance with all required dependencies
|
||||
|
|
@ -58,6 +59,7 @@ func NewSessionService(cfg *config.Config,
|
|||
agentService interfaces.AgentService,
|
||||
sessionStorage llmcontext.ContextStorage,
|
||||
webSearchStateRepo interfaces.WebSearchStateService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) interfaces.SessionService {
|
||||
return &sessionService{
|
||||
cfg: cfg,
|
||||
|
|
@ -72,6 +74,7 @@ func NewSessionService(cfg *config.Config,
|
|||
agentService: agentService,
|
||||
sessionStorage: sessionStorage,
|
||||
webSearchStateRepo: webSearchStateRepo,
|
||||
kbShareService: kbShareService,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -301,7 +304,7 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
|||
chat.Message{Role: "system", Content: s.cfg.Conversation.GenerateSessionTitlePrompt},
|
||||
)
|
||||
chatMessages = append(chatMessages,
|
||||
chat.Message{Role: "user", Content: message.Content + " /no_think"},
|
||||
chat.Message{Role: "user", Content: message.Content},
|
||||
)
|
||||
|
||||
// Call model to generate title
|
||||
|
|
@ -729,10 +732,10 @@ func (s *sessionService) selectChatModelID(
|
|||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) (string, error) {
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs (include shared KB files)
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for model selection: %v", err)
|
||||
} else {
|
||||
|
|
@ -818,16 +821,38 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
|||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
// Get own knowledge bases
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
|
||||
return nil
|
||||
}
|
||||
kbIDSet := make(map[string]bool)
|
||||
kbIDs := make([]string, 0, len(allKBs))
|
||||
for _, kb := range allKBs {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
kbIDSet[kb.ID] = true
|
||||
}
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases", len(kbIDs))
|
||||
|
||||
// Also include shared knowledge bases the user has access to
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
|
||||
return kbIDs
|
||||
case "selected":
|
||||
logger.Infof(ctx, "KBSelectionMode=selected: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
|
|
@ -901,7 +926,7 @@ func (s *sessionService) configureSkillsFromAgent(
|
|||
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
|
||||
// This is called once at the request entry point to avoid repeated queries later in the pipeline
|
||||
// Logic:
|
||||
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target
|
||||
// - For each knowledgeBaseID: create a SearchTargetTypeKnowledgeBase target with correct TenantID
|
||||
// - For each knowledgeID: find its knowledgeBaseID, if the KB is already in the list, skip (covered by full KB search)
|
||||
// otherwise create a SearchTargetTypeKnowledge target grouped by KB
|
||||
func (s *sessionService) buildSearchTargets(
|
||||
|
|
@ -912,30 +937,69 @@ func (s *sessionService) buildSearchTargets(
|
|||
) (types.SearchTargets, error) {
|
||||
var targets types.SearchTargets
|
||||
|
||||
// Build a map from KB ID to TenantID for all KBs we need to process
|
||||
kbTenantMap := make(map[string]uint64)
|
||||
|
||||
// Track which KBs are fully searched
|
||||
fullKBSet := make(map[string]bool)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
fullKBSet[kbID] = true
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
})
|
||||
|
||||
// First pass: process knowledge base IDs and get their tenant info
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
// Get KB details to determine their actual tenant IDs (may include shared KBs)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
fullKBSet[kbID] = true
|
||||
// Try to get KB info - first from current tenant, then from shared access
|
||||
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
// May be a shared KB from another tenant - use kbShareService to check
|
||||
if s.kbShareService != nil {
|
||||
userID, _ := ctx.Value(types.UserIDContextKey).(string)
|
||||
if userID != "" {
|
||||
// Check if user has at least viewer permission on this KB
|
||||
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if hasAccess {
|
||||
// Get KB info without tenant filter
|
||||
kbInfo, err := s.knowledgeBaseService.GetKnowledgeBaseByIDOnly(ctx, kbID)
|
||||
if err == nil && kbInfo != nil {
|
||||
kbTenantMap[kbID] = kbInfo.TenantID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if kb != nil {
|
||||
kbTenantMap[kbID] = kb.TenantID
|
||||
}
|
||||
// Default to current tenant if we couldn't determine the actual tenant
|
||||
if kbTenantMap[kbID] == 0 {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenantMap[kbID],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Process individual knowledge IDs
|
||||
// Process individual knowledge IDs (include shared KB files the user has access to)
|
||||
if len(knowledgeIDs) > 0 {
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for search targets: %v", err)
|
||||
return targets, nil // Return what we have, don't fail
|
||||
}
|
||||
|
||||
// Group knowledge IDs by their KB, excluding those already covered by full KB search
|
||||
// Also track KB tenant IDs from knowledge items
|
||||
kbToKnowledgeIDs := make(map[string][]string)
|
||||
for _, k := range knowledgeList {
|
||||
if k == nil || k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
// Track KB -> TenantID mapping from knowledge items
|
||||
if kbTenantMap[k.KnowledgeBaseID] == 0 {
|
||||
kbTenantMap[k.KnowledgeBaseID] = k.TenantID
|
||||
}
|
||||
// Skip if this KB is already fully searched
|
||||
if fullKBSet[k.KnowledgeBaseID] {
|
||||
continue
|
||||
|
|
@ -945,16 +1009,21 @@ func (s *sessionService) buildSearchTargets(
|
|||
|
||||
// Create SearchTargetTypeKnowledge targets for each KB with specific files
|
||||
for kbID, kidList := range kbToKnowledgeIDs {
|
||||
kbTenant := kbTenantMap[kbID]
|
||||
if kbTenant == 0 {
|
||||
kbTenant = tenantID // fallback
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledge,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenant,
|
||||
KnowledgeIDs: kidList,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs))
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB, kbTenantMap=%v",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs), kbTenantMap)
|
||||
|
||||
return targets, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ type knowledgeTagService struct {
|
|||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
modelService interfaces.ModelService
|
||||
task *asynq.Client
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewKnowledgeTagService creates a new tag service.
|
||||
|
|
@ -37,6 +38,7 @@ func NewKnowledgeTagService(
|
|||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
modelService interfaces.ModelService,
|
||||
task *asynq.Client,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) (interfaces.KnowledgeTagService, error) {
|
||||
return &knowledgeTagService{
|
||||
kbService: kbService,
|
||||
|
|
@ -46,6 +48,7 @@ func NewKnowledgeTagService(
|
|||
retrieveEngine: retrieveEngine,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
kbShareService: kbShareService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -63,14 +66,33 @@ func (s *knowledgeTagService) ListTags(
|
|||
page = &types.Pagination{}
|
||||
}
|
||||
keyword = strings.TrimSpace(keyword)
|
||||
// Ensure KB exists and belongs to current tenant
|
||||
// Ensure KB exists
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := kb.TenantID
|
||||
|
||||
tags, total, err := s.repo.ListByKB(ctx, tenantID, kbID, page, keyword)
|
||||
// Check access permission
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if kb.TenantID != tenantID {
|
||||
// Get user ID from context
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
userID := userIDVal.(string)
|
||||
|
||||
// Check if user has at least viewer permission through organization sharing
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if err != nil || !hasPermission {
|
||||
return nil, werrors.NewForbiddenError("无权访问该知识库")
|
||||
}
|
||||
}
|
||||
|
||||
// Use kb's tenant ID for data access
|
||||
effectiveTenantID := kb.TenantID
|
||||
|
||||
tags, total, err := s.repo.ListByKB(ctx, effectiveTenantID, kbID, page, keyword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -88,7 +110,7 @@ func (s *knowledgeTagService) ListTags(
|
|||
}
|
||||
|
||||
// Batch query all reference counts in 2 SQL queries instead of 2*N
|
||||
countsMap, err := s.repo.BatchCountReferences(ctx, tenantID, kbID, tagIDs)
|
||||
countsMap, err := s.repo.BatchCountReferences(ctx, effectiveTenantID, kbID, tagIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
|
|
|
|||
|
|
@ -426,3 +426,11 @@ func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) {
|
|||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// SearchUsers searches users by username or email
|
||||
func (s *userService) SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error) {
|
||||
if query == "" {
|
||||
return []*types.User{}, nil
|
||||
}
|
||||
return s.userRepo.SearchUsers(ctx, query, limit)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -202,6 +202,9 @@ func formatPipelineLogValue(value interface{}) string {
|
|||
return strconv.Quote(truncatePipelineValue(v))
|
||||
case fmt.Stringer:
|
||||
return strconv.Quote(truncatePipelineValue(v.String()))
|
||||
case json.RawMessage:
|
||||
bytes, _ := v.MarshalJSON()
|
||||
return string(bytes)
|
||||
default:
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,6 +111,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
|||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
must(container.Provide(repository.NewCustomAgentRepository))
|
||||
must(container.Provide(repository.NewOrganizationRepository))
|
||||
must(container.Provide(repository.NewKBShareRepository))
|
||||
must(container.Provide(service.NewWebSearchStateService))
|
||||
|
||||
// MCP manager for managing MCP client connections
|
||||
|
|
@ -121,6 +123,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
|||
logger.Debugf(ctx, "[Container] Registering business services...")
|
||||
must(container.Provide(service.NewTenantService))
|
||||
must(container.Provide(service.NewKnowledgeBaseService))
|
||||
must(container.Provide(service.NewOrganizationService))
|
||||
must(container.Provide(service.NewKBShareService)) // KBShareService must be registered before KnowledgeService and KnowledgeTagService
|
||||
must(container.Provide(service.NewKnowledgeService))
|
||||
must(container.Provide(service.NewChunkService))
|
||||
must(container.Provide(service.NewKnowledgeTagService))
|
||||
|
|
@ -199,6 +203,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
|||
must(container.Provide(handler.NewCustomAgentHandler))
|
||||
must(container.Provide(service.NewSkillService))
|
||||
must(container.Provide(handler.NewSkillHandler))
|
||||
must(container.Provide(handler.NewOrganizationHandler))
|
||||
logger.Debugf(ctx, "[Container] HTTP handlers registered")
|
||||
|
||||
// Router configuration
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
|
|
@ -14,17 +15,48 @@ import (
|
|||
|
||||
// ChunkHandler defines HTTP handlers for chunk operations
|
||||
type ChunkHandler struct {
|
||||
service interfaces.ChunkService
|
||||
service interfaces.ChunkService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewChunkHandler creates a new chunk handler
|
||||
func NewChunkHandler(service interfaces.ChunkService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service}
|
||||
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService) *ChunkHandler {
|
||||
return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKnowledge resolves knowledge by ID, validates KB access (owner or shared with required role), and returns context with effectiveTenantID for downstream service calls.
|
||||
func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID string, requiredPermission types.OrgMemberRole) (context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("Knowledge not found")
|
||||
}
|
||||
if knowledge.TenantID == tenantID {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
if !userExists || h.kbShareService == nil {
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
||||
if permErr != nil || !isShared {
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
if !permission.HasPermission(requiredPermission) {
|
||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
}
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
||||
}
|
||||
|
||||
// GetChunkByIDOnly godoc
|
||||
// @Summary 通过ID获取分块
|
||||
// @Description 仅通过分块ID获取分块详情(不需要knowledge_id)
|
||||
// @Description 仅通过分块ID获取分块详情(不需要knowledge_id);支持共享知识库下的分块访问
|
||||
// @Tags 分块管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
|
|
@ -46,18 +78,8 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving chunk by ID, chunk ID: %s, tenant ID: %d", chunkID, tenantID)
|
||||
|
||||
// Get chunk by ID
|
||||
chunk, err := h.service.GetChunkByID(ctx, chunkID)
|
||||
// Get chunk by ID without tenant filter (chunk may belong to shared KB)
|
||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
|
||||
|
|
@ -69,14 +91,9 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Validate tenant ID
|
||||
if chunk.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access chunk, chunk ID: %s, req tenant: %d, chunk tenant: %d",
|
||||
chunkID, tenantID.(uint64), chunk.TenantID,
|
||||
)
|
||||
c.Error(errors.NewForbiddenError("No permission to access this chunk"))
|
||||
_, err = h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -116,6 +133,12 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse pagination parameters
|
||||
var pagination types.Pagination
|
||||
if err := c.ShouldBindQuery(&pagination); err != nil {
|
||||
|
|
@ -135,8 +158,8 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
|||
|
||||
chunkType := []types.ChunkType{types.ChunkTypeText}
|
||||
|
||||
// Use pagination for query
|
||||
result, err := h.service.ListPagedChunksByKnowledgeID(ctx, knowledgeID, &pagination, chunkType)
|
||||
// Use pagination for query (effCtx has effectiveTenantID for shared KB)
|
||||
result, err := h.service.ListPagedChunksByKnowledgeID(effCtx, knowledgeID, &pagination, chunkType)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
|
|
@ -170,59 +193,46 @@ type UpdateChunkRequest struct {
|
|||
ImageInfo string `json:"image_info"`
|
||||
}
|
||||
|
||||
// validateAndGetChunk validates request parameters and retrieves the chunk
|
||||
// Returns chunk information, knowledge ID, and error
|
||||
func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string, error) {
|
||||
// validateAndGetChunk validates request parameters and retrieves the chunk (supports shared KB via effectiveTenantID).
|
||||
// Returns chunk, knowledge ID, context with effectiveTenantID for downstream calls, and error.
|
||||
func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string, context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Validate knowledge ID
|
||||
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
|
||||
if knowledgeID == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge ID cannot be empty")
|
||||
return nil, "", nil, errors.NewBadRequestError("Knowledge ID cannot be empty")
|
||||
}
|
||||
|
||||
// Validate chunk ID
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Chunk ID is empty")
|
||||
return nil, knowledgeID, errors.NewBadRequestError("Chunk ID cannot be empty")
|
||||
return nil, knowledgeID, nil, errors.NewBadRequestError("Chunk ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, knowledgeID, errors.NewUnauthorizedError("Unauthorized")
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
return nil, knowledgeID, nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving knowledge chunk information, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
|
||||
// Get existing chunk
|
||||
chunk, err := h.service.GetChunkByID(ctx, id)
|
||||
chunk, err := h.service.GetChunkByID(effCtx, id)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
return nil, knowledgeID, errors.NewNotFoundError("Chunk not found")
|
||||
return nil, knowledgeID, nil, errors.NewNotFoundError("Chunk not found")
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, knowledgeID, errors.NewInternalServerError(err.Error())
|
||||
return nil, knowledgeID, nil, errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Validate tenant ID
|
||||
if chunk.TenantID != tenantID.(uint64) || chunk.KnowledgeID != knowledgeID {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access chunk, knowledge ID: %s, chunk ID: %s, req tenant: %d, chunk tenant: %d",
|
||||
knowledgeID,
|
||||
id,
|
||||
tenantID,
|
||||
chunk.TenantID,
|
||||
)
|
||||
return nil, knowledgeID, errors.NewForbiddenError("No permission to access this chunk")
|
||||
if chunk.KnowledgeID != knowledgeID {
|
||||
logger.Warnf(ctx, "Chunk does not belong to knowledge, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||
return nil, knowledgeID, nil, errors.NewForbiddenError("No permission to access this chunk")
|
||||
}
|
||||
|
||||
return chunk, knowledgeID, nil
|
||||
return chunk, knowledgeID, effCtx, nil
|
||||
}
|
||||
|
||||
// UpdateChunk godoc
|
||||
|
|
@ -244,8 +254,7 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating knowledge chunk")
|
||||
|
||||
// Validate parameters and get chunk
|
||||
chunk, knowledgeID, err := h.validateAndGetChunk(c)
|
||||
chunk, knowledgeID, effCtx, err := h.validateAndGetChunk(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
|
|
@ -257,14 +266,13 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Update chunk properties
|
||||
if req.Content != "" {
|
||||
chunk.Content = req.Content
|
||||
}
|
||||
|
||||
chunk.IsEnabled = req.IsEnabled
|
||||
|
||||
if err := h.service.UpdateChunk(ctx, chunk); err != nil {
|
||||
if err := h.service.UpdateChunk(effCtx, chunk); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
|
|
@ -296,14 +304,13 @@ func (h *ChunkHandler) DeleteChunk(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start deleting knowledge chunk")
|
||||
|
||||
// Validate parameters and get chunk
|
||||
chunk, _, err := h.validateAndGetChunk(c)
|
||||
chunk, _, effCtx, err := h.validateAndGetChunk(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.DeleteChunk(ctx, chunk.ID); err != nil {
|
||||
if err := h.service.DeleteChunk(effCtx, chunk.ID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
|
|
@ -338,8 +345,13 @@ func (h *ChunkHandler) DeleteChunksByKnowledgeID(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Delete all chunks under the knowledge
|
||||
err := h.service.DeleteChunksByKnowledgeID(ctx, knowledgeID)
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.DeleteChunksByKnowledgeID(effCtx, knowledgeID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
|
|
@ -386,16 +398,7 @@ func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
|
||||
// Verify chunk exists and belongs to tenant
|
||||
chunk, err := h.service.GetChunkByID(ctx, chunkID)
|
||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
||||
if err != nil {
|
||||
if err == service.ErrChunkNotFound {
|
||||
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
|
||||
|
|
@ -407,14 +410,13 @@ func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
if chunk.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(ctx, "Tenant has no permission to access chunk, chunk ID: %s", chunkID)
|
||||
c.Error(errors.NewForbiddenError("No permission to access this chunk"))
|
||||
effCtx, err := h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the generated question by ID
|
||||
if err := h.service.DeleteGeneratedQuestion(ctx, chunkID, req.QuestionID); err != nil {
|
||||
if err := h.service.DeleteGeneratedQuestion(effCtx, chunkID, req.QuestionID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -18,50 +19,156 @@ import (
|
|||
|
||||
// KnowledgeHandler processes HTTP requests related to knowledge resources
|
||||
type KnowledgeHandler struct {
|
||||
kgService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kgService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// NewKnowledgeHandler creates a new knowledge handler instance
|
||||
func NewKnowledgeHandler(
|
||||
kgService interfaces.KnowledgeService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) *KnowledgeHandler {
|
||||
return &KnowledgeHandler{kgService: kgService, kbService: kbService}
|
||||
return &KnowledgeHandler{
|
||||
kgService: kgService,
|
||||
kbService: kbService,
|
||||
kbShareService: kbShareService,
|
||||
}
|
||||
}
|
||||
|
||||
// validateKnowledgeBaseAccess validates access permissions to a knowledge base
|
||||
// Returns the knowledge base, the knowledge base ID, and any errors encountered
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, error) {
|
||||
// Returns the knowledge base, the knowledge base ID, effective tenant ID, permission level, and any errors encountered
|
||||
// For owned KBs, effectiveTenantID is the caller's tenant ID
|
||||
// For shared KBs, effectiveTenantID is the source tenant ID (owner's tenant)
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
|
||||
// Get user ID from context (needed for shared KB permission check)
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
// Get knowledge base ID from URL path parameter
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
if kbID == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
// Get knowledge base details
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, kbID, errors.NewInternalServerError(err.Error())
|
||||
return nil, kbID, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Verify tenant permissions
|
||||
if kb.TenantID != c.GetUint64(types.TenantIDContextKey.String()) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Permission denied to access this knowledge base, tenant ID mismatch, "+
|
||||
"requested tenant ID: %d, knowledge base tenant ID: %d",
|
||||
c.GetUint64(types.TenantIDContextKey.String()),
|
||||
kb.TenantID,
|
||||
)
|
||||
return nil, kbID, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
// Check 1: Verify tenant ownership (owner has full access)
|
||||
if kb.TenantID == tenantID {
|
||||
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
return kb, kbID, nil
|
||||
// Check 2: If not owner, check organization shared access
|
||||
if userExists && h.kbShareService != nil {
|
||||
// Check if user has shared access through organization
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
// User has shared access, get the source tenant ID for queries
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), kbID, permission, sourceTenantID)
|
||||
return kb, kbID, sourceTenantID, permission, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No permission: not owner and no shared access
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Permission denied to access this knowledge base, tenant ID mismatch, "+
|
||||
"requested tenant ID: %d, knowledge base tenant ID: %d",
|
||||
tenantID,
|
||||
kb.TenantID,
|
||||
)
|
||||
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// validateKnowledgeBaseAccessWithKBID validates access to the given knowledge base ID (e.g. from query or body).
|
||||
// Returns the knowledge base, kbID, effective tenant ID, permission, and error.
|
||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, kbID string) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
kbID = secutils.SanitizeForLog(kbID)
|
||||
if kbID == "" {
|
||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, kbID, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
if kb.TenantID == tenantID {
|
||||
return kb, kbID, tenantID, types.OrgRoleAdmin, nil
|
||||
}
|
||||
if userExists && h.kbShareService != nil {
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), kbID, permission, sourceTenantID)
|
||||
return kb, kbID, sourceTenantID, permission, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID)
|
||||
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// resolveKnowledgeAndValidateKBAccess resolves knowledge by ID and validates KB access (owner or shared with required permission).
|
||||
// Returns the knowledge, context with effectiveTenantID set for downstream service calls, and error.
|
||||
func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, knowledgeID string, requiredPermission types.OrgMemberRole) (*types.Knowledge, context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
return nil, ctx, errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
return nil, ctx, errors.NewNotFoundError("Knowledge not found")
|
||||
}
|
||||
|
||||
// Owner: knowledge belongs to caller's tenant
|
||||
if knowledge.TenantID == tenantID {
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
|
||||
// Shared KB: check organization permission
|
||||
if !userExists || h.kbShareService == nil {
|
||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
|
||||
if permErr != nil || !isShared {
|
||||
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
|
||||
}
|
||||
if !permission.HasPermission(requiredPermission) {
|
||||
return nil, ctx, errors.NewForbiddenError("Insufficient permission for this operation")
|
||||
}
|
||||
effectiveTenantID := knowledge.TenantID
|
||||
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
|
||||
}
|
||||
|
||||
// handleDuplicateKnowledgeError handles cases where duplicate knowledge is detected
|
||||
|
|
@ -104,12 +211,19 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating knowledge from file")
|
||||
|
||||
// Validate access to the knowledge base
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
// Get the uploaded file
|
||||
file, err := c.FormFile("file")
|
||||
|
|
@ -217,12 +331,19 @@ func (h *KnowledgeHandler) CreateKnowledgeFromURL(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating knowledge from URL")
|
||||
|
||||
// Validate access to the knowledge base
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse URL from request body
|
||||
var req struct {
|
||||
|
|
@ -286,11 +407,19 @@ func (h *KnowledgeHandler) CreateManualKnowledge(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating manual knowledge")
|
||||
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
// Validate access to the knowledge base (only owner or admin/editor can create)
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Check write permission
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to create knowledge"))
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
|
|
@ -338,7 +467,6 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
|||
|
||||
logger.Info(ctx, "Start retrieving knowledge")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
|
|
@ -346,20 +474,15 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Retrieving knowledge, ID: %s", secutils.SanitizeForLog(id))
|
||||
knowledge, err := h.kgService.GetKnowledgeByID(ctx, id)
|
||||
// Resolve knowledge and validate KB access (at least viewer)
|
||||
knowledge, _, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge retrieved successfully, ID: %s, title: %s",
|
||||
secutils.SanitizeForLog(knowledge.ID),
|
||||
secutils.SanitizeForLog(knowledge.Title),
|
||||
)
|
||||
logger.Infof(ctx, "Knowledge retrieved successfully, ID: %s, title: %s",
|
||||
secutils.SanitizeForLog(knowledge.ID), secutils.SanitizeForLog(knowledge.Title))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledge,
|
||||
|
|
@ -388,14 +511,16 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
|||
|
||||
logger.Info(ctx, "Start retrieving knowledge list")
|
||||
|
||||
// Get knowledge base ID from URL path parameter
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
if kbID == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Knowledge base ID cannot be empty"))
|
||||
// Validate access to the knowledge base (read access - any permission level)
|
||||
_, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Update context with effective tenant ID for shared KB access
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Parse pagination parameters from query string
|
||||
var pagination types.Pagination
|
||||
if err := c.ShouldBindQuery(&pagination); err != nil {
|
||||
|
|
@ -410,13 +535,14 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
|
|||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d",
|
||||
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d, effectiveTenantID: %d",
|
||||
secutils.SanitizeForLog(kbID),
|
||||
secutils.SanitizeForLog(tagID),
|
||||
secutils.SanitizeForLog(keyword),
|
||||
secutils.SanitizeForLog(fileType),
|
||||
pagination.Page,
|
||||
pagination.PageSize,
|
||||
effectiveTenantID,
|
||||
)
|
||||
|
||||
// Retrieve paginated knowledge entries
|
||||
|
|
@ -459,7 +585,6 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
|
|||
|
||||
logger.Info(ctx, "Start deleting knowledge")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
|
|
@ -467,8 +592,13 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Deleting knowledge, ID: %s", secutils.SanitizeForLog(id))
|
||||
err := h.kgService.DeleteKnowledge(ctx, id)
|
||||
err = h.kgService.DeleteKnowledge(effCtx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
|
|
@ -499,7 +629,6 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
|||
|
||||
logger.Info(ctx, "Start downloading knowledge file")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
|
|
@ -507,10 +636,14 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Retrieving knowledge file, ID: %s", secutils.SanitizeForLog(id))
|
||||
|
||||
// Get file content and filename
|
||||
file, filename, err := h.kgService.GetKnowledgeFile(ctx, id)
|
||||
file, filename, err := h.kgService.GetKnowledgeFile(effCtx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to retrieve file").WithDetails(err.Error()))
|
||||
|
|
@ -547,33 +680,34 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) {
|
|||
|
||||
// GetKnowledgeBatchRequest defines parameters for batch knowledge retrieval
|
||||
type GetKnowledgeBatchRequest struct {
|
||||
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
|
||||
IDs []string `form:"ids" binding:"required"` // List of knowledge IDs
|
||||
KBID string `form:"kb_id"` // Optional: scope to this KB (validates access and uses effective tenant for shared KB)
|
||||
}
|
||||
|
||||
// GetKnowledgeBatch godoc
|
||||
// @Summary 批量获取知识
|
||||
// @Description 根据ID列表批量获取知识条目
|
||||
// @Description 根据ID列表批量获取知识条目。可选 kb_id:指定时按该知识库校验权限并用于共享知识库的租户解析
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param ids query []string true "知识ID列表"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Param ids query []string true "知识ID列表"
|
||||
// @Param kb_id query string false "可选,知识库ID(用于共享知识库时指定范围)"
|
||||
// @Success 200 {object} map[string]interface{} "知识列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge/batch [get]
|
||||
func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := c.Get(types.TenantIDContextKey.String())
|
||||
if !ok {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
effectiveTenantID := tenantID.(uint64)
|
||||
|
||||
// Parse request parameters from query string
|
||||
var req GetKnowledgeBatchRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
|
|
@ -581,27 +715,41 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Batch retrieving knowledge, tenant ID: %d, number of knowledge IDs: %d",
|
||||
tenantID, len(req.IDs),
|
||||
)
|
||||
var knowledges []*types.Knowledge
|
||||
var err error
|
||||
|
||||
// Optional kb_id: validate KB access and use effective tenant for shared KB
|
||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||
_, _, effID, _, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
effectiveTenantID = effID
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
logger.Infof(ctx, "Batch retrieving knowledge with kb_id, effective tenant ID: %d, IDs count: %d",
|
||||
effectiveTenantID, len(req.IDs))
|
||||
|
||||
knowledges, err = h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, req.IDs)
|
||||
} else {
|
||||
// No kb_id provided: use GetKnowledgeBatchWithSharedAccess to support cross-tenant shared files
|
||||
// This is needed when page is refreshed and frontend doesn't have kb_id mapping
|
||||
logger.Infof(ctx, "Batch retrieving knowledge without kb_id (using shared access), tenant ID: %d, IDs count: %d",
|
||||
effectiveTenantID, len(req.IDs))
|
||||
|
||||
knowledges, err = h.kgService.GetKnowledgeBatchWithSharedAccess(ctx, effectiveTenantID, req.IDs)
|
||||
}
|
||||
|
||||
// Retrieve knowledge entries in batch
|
||||
knowledges, err := h.kgService.GetKnowledgeBatch(ctx, tenantID.(uint64), req.IDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Batch knowledge retrieval successful, requested count: %d, returned count: %d",
|
||||
len(req.IDs), len(knowledges),
|
||||
)
|
||||
logger.Infof(ctx, "Batch knowledge retrieval successful, requested count: %d, returned count: %d",
|
||||
len(req.IDs), len(knowledges))
|
||||
|
||||
// Return results
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledges,
|
||||
|
|
@ -623,7 +771,7 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||
// @Router /knowledge/{id} [put]
|
||||
func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
// Get knowledge ID from URL path parameter
|
||||
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
|
|
@ -631,14 +779,21 @@ func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var knowledge types.Knowledge
|
||||
if err := c.ShouldBindJSON(&knowledge); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
knowledge.ID = id
|
||||
|
||||
if err := h.kgService.UpdateKnowledge(ctx, &knowledge); err != nil {
|
||||
if err := h.kgService.UpdateKnowledge(effCtx, &knowledge); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
|
|
@ -675,6 +830,12 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse manual knowledge update request", err)
|
||||
|
|
@ -682,7 +843,7 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
knowledge, err := h.kgService.UpdateManualKnowledge(ctx, id, &req)
|
||||
knowledge, err := h.kgService.UpdateManualKnowledge(effCtx, id, &req)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
|
|
@ -704,15 +865,16 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
|||
|
||||
type knowledgeTagBatchRequest struct {
|
||||
Updates map[string]*string `json:"updates" binding:"required,min=1"`
|
||||
KBID string `json:"kb_id"` // Optional: scope to this KB (validates editor access and uses effective tenant for shared KB)
|
||||
}
|
||||
|
||||
// UpdateKnowledgeTagBatch godoc
|
||||
// @Summary 批量更新知识标签
|
||||
// @Description 批量更新知识条目的标签
|
||||
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的租户解析
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body object true "标签更新请求"
|
||||
// @Param request body object true "标签更新请求(updates 必填,kb_id 可选)"
|
||||
// @Success 200 {object} map[string]interface{} "更新成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
|
|
@ -720,12 +882,49 @@ type knowledgeTagBatchRequest struct {
|
|||
// @Router /knowledge/tags [put]
|
||||
func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Ensure tenant ID is in context (service reads it; may be missing if request context was not set by auth)
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
c.Error(errors.NewUnauthorizedError("Unauthorized"))
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
|
||||
|
||||
var req knowledgeTagBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse knowledge tag batch request", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
// Resolve effective tenant: explicit kb_id, or infer from first knowledge ID (for shared KB when frontend doesn't send kb_id)
|
||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||
_, _, effID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effID)
|
||||
} else if len(req.Updates) > 0 {
|
||||
// No kb_id: infer from first knowledge ID so shared-KB updates work without client sending kb_id
|
||||
var firstKnowledgeID string
|
||||
for id := range req.Updates {
|
||||
firstKnowledgeID = id
|
||||
break
|
||||
}
|
||||
if firstKnowledgeID != "" {
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
ctx = effCtx
|
||||
}
|
||||
}
|
||||
if err := h.kgService.UpdateKnowledgeTagBatch(ctx, req.Updates); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
|
|
@ -754,7 +953,6 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating image info")
|
||||
|
||||
// Get knowledge ID from URL path parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
|
|
@ -768,6 +966,12 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var request struct {
|
||||
ImageInfo string `json:"image_info"`
|
||||
}
|
||||
|
|
@ -778,9 +982,8 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Update chunk properties
|
||||
logger.Infof(ctx, "Updating knowledge chunk, knowledge ID: %s, chunk ID: %s", id, chunkID)
|
||||
err := h.kgService.UpdateImageInfo(ctx, id, chunkID, secutils.SanitizeForLog(request.ImageInfo))
|
||||
err = h.kgService.UpdateImageInfo(effCtx, id, chunkID, secutils.SanitizeForLog(request.ImageInfo))
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
|
|
@ -811,6 +1014,9 @@ func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
|||
// @Router /knowledge/search [get]
|
||||
func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if userID, ok := c.Get(types.UserIDContextKey.String()); ok {
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
|
||||
}
|
||||
keyword := c.Query("keyword")
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
|
||||
|
|
@ -826,7 +1032,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
// Retrieve knowledge entries (empty keyword returns recent files)
|
||||
// Retrieve knowledge entries (own + shared KBs; empty keyword returns recent files)
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import (
|
|||
type KnowledgeBaseHandler struct {
|
||||
service interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
kbShareService interfaces.KBShareService
|
||||
asynqClient *asynq.Client
|
||||
}
|
||||
|
||||
|
|
@ -29,11 +30,13 @@ type KnowledgeBaseHandler struct {
|
|||
func NewKnowledgeBaseHandler(
|
||||
service interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
asynqClient *asynq.Client,
|
||||
) *KnowledgeBaseHandler {
|
||||
return &KnowledgeBaseHandler{
|
||||
service: service,
|
||||
knowledgeService: knowledgeService,
|
||||
kbShareService: kbShareService,
|
||||
asynqClient: asynqClient,
|
||||
}
|
||||
}
|
||||
|
|
@ -56,11 +59,10 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
|
|||
|
||||
logger.Info(ctx, "Start hybrid search")
|
||||
|
||||
// Validate knowledge base ID
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Knowledge base ID cannot be empty"))
|
||||
// Validate and check permission for knowledge base access
|
||||
_, id, effectiveTenantID, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -72,10 +74,11 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Executing hybrid search, knowledge base ID: %s, query: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.QueryText))
|
||||
logger.Infof(ctx, "Executing hybrid search, knowledge base ID: %s, query: %s, effectiveTenantID: %d",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.QueryText), effectiveTenantID)
|
||||
|
||||
// Execute hybrid search with default search parameters
|
||||
// Note: For shared KBs, the service uses effectiveTenantID internally via context
|
||||
results, err := h.service.HybridSearch(ctx, id, req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
|
|
@ -139,43 +142,64 @@ func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
|
|||
}
|
||||
|
||||
// validateAndGetKnowledgeBase validates request parameters and retrieves the knowledge base
|
||||
// Returns the knowledge base, knowledge base ID, and any errors encountered
|
||||
func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*types.KnowledgeBase, string, error) {
|
||||
// Returns the knowledge base, knowledge base ID, effective tenant ID for embedding, permission level, and any errors encountered
|
||||
// For owned KBs, effectiveTenantID is the caller's tenant ID
|
||||
// For shared KBs, effectiveTenantID is the source tenant ID (owner's tenant)
|
||||
func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Failed to get tenant ID")
|
||||
return nil, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
return nil, "", 0, "", errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
|
||||
// Get user ID from context (needed for shared KB permission check)
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
|
||||
// Get knowledge base ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Knowledge base ID is empty")
|
||||
return nil, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
return nil, "", 0, "", errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
|
||||
// Verify tenant has permission to access this knowledge base
|
||||
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, id, errors.NewInternalServerError(err.Error())
|
||||
return nil, id, 0, "", errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
|
||||
// Verify tenant ownership
|
||||
if kb.TenantID != tenantID.(uint64) {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access this knowledge base, knowledge base ID: %s, "+
|
||||
"request tenant ID: %d, knowledge base tenant ID: %d",
|
||||
id, tenantID.(uint64), kb.TenantID,
|
||||
)
|
||||
return nil, id, errors.NewForbiddenError("No permission to operate")
|
||||
// Check 1: Verify tenant ownership (owner has full access)
|
||||
if kb.TenantID == tenantID.(uint64) {
|
||||
return kb, id, tenantID.(uint64), types.OrgRoleAdmin, nil
|
||||
}
|
||||
|
||||
return kb, id, nil
|
||||
// Check 2: If not owner, check organization shared access
|
||||
if userExists && h.kbShareService != nil {
|
||||
// Check if user has shared access through organization
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, id, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
// User has shared access, get the source tenant ID for embedding queries
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, id)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), id, permission, sourceTenantID)
|
||||
return kb, id, sourceTenantID, permission, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No permission: not owner and no shared access
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Tenant has no permission to access this knowledge base, knowledge base ID: %s, "+
|
||||
"request tenant ID: %d, knowledge base tenant ID: %d",
|
||||
id, tenantID.(uint64), kb.TenantID,
|
||||
)
|
||||
return nil, id, 0, "", errors.NewForbiddenError("No permission to operate")
|
||||
}
|
||||
|
||||
// GetKnowledgeBase godoc
|
||||
|
|
@ -193,7 +217,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||
// @Router /knowledge-bases/{id} [get]
|
||||
func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
|
||||
// Validate and get the knowledge base
|
||||
kb, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
kb, _, _, _, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
|
|
@ -226,6 +250,25 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Get share counts for all knowledge bases
|
||||
if len(kbs) > 0 && h.kbShareService != nil {
|
||||
kbIDs := make([]string, len(kbs))
|
||||
for i, kb := range kbs {
|
||||
kbIDs[i] = kb.ID
|
||||
}
|
||||
|
||||
shareCounts, err := h.kbShareService.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get share counts: %v", err)
|
||||
} else {
|
||||
for _, kb := range kbs {
|
||||
if count, ok := shareCounts[kb.ID]; ok {
|
||||
kb.ShareCount = count
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": kbs,
|
||||
|
|
@ -257,12 +300,18 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
|
|||
logger.Info(ctx, "Start updating knowledge base")
|
||||
|
||||
// Validate and get the knowledge base
|
||||
_, id, err := h.validateAndGetKnowledgeBase(c)
|
||||
_, id, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Only admin/editor can update knowledge base
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to update knowledge base"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var req UpdateKnowledgeBaseRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
|
|
@ -307,12 +356,19 @@ func (h *KnowledgeBaseHandler) DeleteKnowledgeBase(c *gin.Context) {
|
|||
logger.Info(ctx, "Start deleting knowledge base")
|
||||
|
||||
// Validate and get the knowledge base
|
||||
kb, id, err := h.validateAndGetKnowledgeBase(c)
|
||||
kb, id, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Only owner (admin with matching tenant) can delete knowledge base
|
||||
tenantID, _ := c.Get(types.TenantIDContextKey.String())
|
||||
if kb.TenantID != tenantID.(uint64) || permission != types.OrgRoleAdmin {
|
||||
c.Error(errors.NewForbiddenError("Only knowledge base owner can delete"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Deleting knowledge base, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(kb.Name))
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -86,6 +86,48 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
|||
}
|
||||
}
|
||||
|
||||
// Merge @mentioned items into knowledge_base_ids and knowledge_ids so that
|
||||
// retrieval (quick-answer and agent mode) uses the same targets the user @mentioned.
|
||||
// This fixes the case where user only @mentions a (shared) KB in the input but
|
||||
// does not select it in the sidebar — without this merge, retrieval would not search those KBs.
|
||||
kbIDs := make([]string, 0, len(request.KnowledgeBaseIDs)+len(request.MentionedItems))
|
||||
kbIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeBaseIDs {
|
||||
if id != "" && !kbIDSet[id] {
|
||||
kbIDs = append(kbIDs, id)
|
||||
kbIDSet[id] = true
|
||||
}
|
||||
}
|
||||
knowledgeIDs := make([]string, 0, len(request.KnowledgeIds)+len(request.MentionedItems))
|
||||
knowledgeIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeIds {
|
||||
if id != "" && !knowledgeIDSet[id] {
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
knowledgeIDSet[id] = true
|
||||
}
|
||||
}
|
||||
for _, item := range request.MentionedItems {
|
||||
if item.ID == "" {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case "kb":
|
||||
if !kbIDSet[item.ID] {
|
||||
kbIDs = append(kbIDs, item.ID)
|
||||
kbIDSet[item.ID] = true
|
||||
}
|
||||
case "file":
|
||||
if !knowledgeIDSet[item.ID] {
|
||||
knowledgeIDs = append(knowledgeIDs, item.ID)
|
||||
knowledgeIDSet[item.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log merge results for debugging
|
||||
logger.Infof(ctx, "[%s] @mention merge: request.KnowledgeBaseIDs=%v, request.MentionedItems=%d, merged kbIDs=%v, merged knowledgeIDs=%v",
|
||||
logPrefix, request.KnowledgeBaseIDs, len(request.MentionedItems), kbIDs, knowledgeIDs)
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
ctx: ctx,
|
||||
|
|
@ -101,8 +143,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
|||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
|
|
|
|||
|
|
@ -16,9 +16,11 @@ import (
|
|||
|
||||
// TagHandler handles knowledge base tag operations.
|
||||
type TagHandler struct {
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
}
|
||||
|
||||
// DeleteTagRequest represents the request body for deleting a tag
|
||||
|
|
@ -27,19 +29,62 @@ type DeleteTagRequest struct {
|
|||
}
|
||||
|
||||
// NewTagHandler creates a new TagHandler.
|
||||
func NewTagHandler(tagService interfaces.KnowledgeTagService, tagRepo interfaces.KnowledgeTagRepository, chunkRepo interfaces.ChunkRepository) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo}
|
||||
func NewTagHandler(
|
||||
tagService interfaces.KnowledgeTagService,
|
||||
tagRepo interfaces.KnowledgeTagRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService}
|
||||
}
|
||||
|
||||
// effectiveCtxForKB validates KB access (owner or shared) and returns context with effectiveTenantID for downstream service calls.
|
||||
func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Context, error) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
return nil, errors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
userID, userExists := c.Get(types.UserIDContextKey.String())
|
||||
kbID = secutils.SanitizeForLog(kbID)
|
||||
if kbID == "" {
|
||||
return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
|
||||
}
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return nil, errors.NewInternalServerError(err.Error())
|
||||
}
|
||||
if kb.TenantID == tenantID {
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
||||
}
|
||||
if userExists && h.kbShareService != nil {
|
||||
permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
|
||||
if permErr == nil && isShared {
|
||||
sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
|
||||
if srcErr == nil {
|
||||
logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
|
||||
userID.(string), kbID, permission, sourceTenantID)
|
||||
return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
|
||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
|
||||
}
|
||||
|
||||
// resolveTagID resolves tag_id parameter which can be either UUID or seq_id (integer).
|
||||
// Returns the UUID of the tag.
|
||||
// Uses tenant from c's context. Use resolveTagIDWithCtx when effectiveTenantID is set (e.g. shared KB).
|
||||
func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) {
|
||||
ctx := c.Request.Context()
|
||||
return h.resolveTagIDWithCtx(c, c.Request.Context())
|
||||
}
|
||||
|
||||
// resolveTagIDWithCtx resolves tag_id using the given context for tenant (e.g. effCtx for shared KB).
|
||||
func (h *TagHandler) resolveTagIDWithCtx(c *gin.Context, ctx context.Context) (string, error) {
|
||||
tagIDParam := secutils.SanitizeForLog(c.Param("tag_id"))
|
||||
|
||||
// Try to parse as integer (seq_id)
|
||||
if seqID, err := strconv.ParseInt(tagIDParam, 10, 64); err == nil {
|
||||
// It's an integer, look up by seq_id
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tag, err := h.tagRepo.GetBySeqID(ctx, tenantID, seqID)
|
||||
if err != nil {
|
||||
|
|
@ -47,8 +92,6 @@ func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) {
|
|||
}
|
||||
return tag.ID, nil
|
||||
}
|
||||
|
||||
// It's a UUID string
|
||||
return tagIDParam, nil
|
||||
}
|
||||
|
||||
|
|
@ -76,6 +119,12 @@ func (h *TagHandler) ListTags(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var page types.Pagination
|
||||
if err := c.ShouldBindQuery(&page); err != nil {
|
||||
logger.Error(ctx, "Failed to bind pagination query", err)
|
||||
|
|
@ -85,7 +134,7 @@ func (h *TagHandler) ListTags(c *gin.Context) {
|
|||
|
||||
keyword := secutils.SanitizeForLog(c.Query("keyword"))
|
||||
|
||||
tags, err := h.tagService.ListTags(ctx, kbID, &page, keyword)
|
||||
tags, err := h.tagService.ListTags(effCtx, kbID, &page, keyword)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
|
|
@ -121,6 +170,12 @@ func (h *TagHandler) CreateTag(c *gin.Context) {
|
|||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req createTagRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind create tag payload", err)
|
||||
|
|
@ -128,7 +183,7 @@ func (h *TagHandler) CreateTag(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
tag, err := h.tagService.CreateTag(ctx, kbID,
|
||||
tag, err := h.tagService.CreateTag(effCtx, kbID,
|
||||
secutils.SanitizeForLog(req.Name), secutils.SanitizeForLog(req.Color), req.SortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
|
|
@ -166,8 +221,15 @@ type updateTagRequest struct {
|
|||
// @Router /knowledge-bases/{id}/tags/{tag_id} [put]
|
||||
func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
tagID, err := h.resolveTagID(c)
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
tagID, err := h.resolveTagIDWithCtx(c, effCtx)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
|
|
@ -180,7 +242,7 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
tag, err := h.tagService.UpdateTag(ctx, tagID, req.Name, req.Color, req.SortOrder)
|
||||
tag, err := h.tagService.UpdateTag(effCtx, tagID, req.Name, req.Color, req.SortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tag_id": tagID,
|
||||
|
|
@ -213,8 +275,15 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
|||
// @Router /knowledge-bases/{id}/tags/{tag_id} [delete]
|
||||
func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
tagID, err := h.resolveTagID(c)
|
||||
effCtx, err := h.effectiveCtxForKB(c, kbID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
tagID, err := h.resolveTagIDWithCtx(c, effCtx)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
|
|
@ -224,14 +293,12 @@ func (h *TagHandler) DeleteTag(c *gin.Context) {
|
|||
contentOnly := c.Query("content_only") == "true"
|
||||
|
||||
var req DeleteTagRequest
|
||||
// Ignore bind error since body is optional
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
|
||||
// Convert seq_ids to UUIDs for excludeIDs
|
||||
var excludeUUIDs []string
|
||||
if len(req.ExcludeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
chunks, err := h.getChunksBySeqIDs(ctx, tenantID, req.ExcludeIDs)
|
||||
tenantID := effCtx.Value(types.TenantIDContextKey).(uint64)
|
||||
chunks, err := h.getChunksBySeqIDs(effCtx, tenantID, req.ExcludeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to resolve exclude_ids: %v", err)
|
||||
} else {
|
||||
|
|
@ -242,7 +309,7 @@ func (h *TagHandler) DeleteTag(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly, excludeUUIDs); err != nil {
|
||||
if err := h.tagService.DeleteTag(effCtx, tagID, force, contentOnly, excludeUUIDs); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tag_id": tagID,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -292,6 +292,8 @@ func CloneContext(ctx context.Context) context.Context {
|
|||
types.TenantIDContextKey,
|
||||
types.RequestIDContextKey,
|
||||
types.TenantInfoContextKey,
|
||||
types.UserIDContextKey,
|
||||
types.UserContextKey,
|
||||
} {
|
||||
if v := ctx.Value(k); v != nil {
|
||||
newCtx = context.WithValue(newCtx, k, v)
|
||||
|
|
|
|||
|
|
@ -131,13 +131,17 @@ func Auth(
|
|||
c.Set(types.TenantIDContextKey.String(), targetTenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), tenant)
|
||||
c.Set(types.UserContextKey.String(), user)
|
||||
c.Set(types.UserIDContextKey.String(), user.ID)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
|
||||
types.TenantInfoContextKey, tenant,
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID),
|
||||
types.TenantInfoContextKey, tenant,
|
||||
),
|
||||
types.UserContextKey, user,
|
||||
),
|
||||
types.UserContextKey, user,
|
||||
types.UserIDContextKey, user.ID,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ type RouterParams struct {
|
|||
TagHandler *handler.TagHandler
|
||||
CustomAgentHandler *handler.CustomAgentHandler
|
||||
SkillHandler *handler.SkillHandler
|
||||
OrganizationHandler *handler.OrganizationHandler
|
||||
}
|
||||
|
||||
// NewRouter 创建新的路由
|
||||
|
|
@ -114,6 +115,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
|
||||
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
|
||||
RegisterSkillRoutes(v1, params.SkillHandler)
|
||||
RegisterOrganizationRoutes(v1, params.OrganizationHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
|
|
@ -450,3 +452,65 @@ func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler)
|
|||
skills.GET("", skillHandler.ListSkills)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterOrganizationRoutes registers organization and sharing routes
|
||||
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler) {
|
||||
// Organization routes
|
||||
orgs := r.Group("/organizations")
|
||||
{
|
||||
// Create organization
|
||||
orgs.POST("", orgHandler.CreateOrganization)
|
||||
// List my organizations
|
||||
orgs.GET("", orgHandler.ListMyOrganizations)
|
||||
// Preview organization by invite code (without joining)
|
||||
orgs.GET("/preview/:code", orgHandler.PreviewByInviteCode)
|
||||
// Join organization by invite code
|
||||
orgs.POST("/join", orgHandler.JoinByInviteCode)
|
||||
// Submit join request (for organizations that require approval)
|
||||
orgs.POST("/join-request", orgHandler.SubmitJoinRequest)
|
||||
// Get organization by ID
|
||||
orgs.GET("/:id", orgHandler.GetOrganization)
|
||||
// Update organization
|
||||
orgs.PUT("/:id", orgHandler.UpdateOrganization)
|
||||
// Delete organization
|
||||
orgs.DELETE("/:id", orgHandler.DeleteOrganization)
|
||||
// Leave organization
|
||||
orgs.POST("/:id/leave", orgHandler.LeaveOrganization)
|
||||
// Request role upgrade (for existing members)
|
||||
orgs.POST("/:id/request-upgrade", orgHandler.RequestRoleUpgrade)
|
||||
// Generate invite code
|
||||
orgs.POST("/:id/invite-code", orgHandler.GenerateInviteCode)
|
||||
// Search users for invite (admin only)
|
||||
orgs.GET("/:id/search-users", orgHandler.SearchUsersForInvite)
|
||||
// Invite member directly (admin only)
|
||||
orgs.POST("/:id/invite", orgHandler.InviteMember)
|
||||
// List members
|
||||
orgs.GET("/:id/members", orgHandler.ListMembers)
|
||||
// Update member role
|
||||
orgs.PUT("/:id/members/:user_id", orgHandler.UpdateMemberRole)
|
||||
// Remove member
|
||||
orgs.DELETE("/:id/members/:user_id", orgHandler.RemoveMember)
|
||||
// List join requests (admin only)
|
||||
orgs.GET("/:id/join-requests", orgHandler.ListJoinRequests)
|
||||
// Review join request (admin only)
|
||||
orgs.PUT("/:id/join-requests/:request_id/review", orgHandler.ReviewJoinRequest)
|
||||
// List knowledge bases shared to this organization
|
||||
orgs.GET("/:id/shares", orgHandler.ListOrgShares)
|
||||
}
|
||||
|
||||
// Knowledge base sharing routes (add to existing kb routes)
|
||||
kbShares := r.Group("/knowledge-bases/:id/shares")
|
||||
{
|
||||
// Share knowledge base
|
||||
kbShares.POST("", orgHandler.ShareKnowledgeBase)
|
||||
// List shares
|
||||
kbShares.GET("", orgHandler.ListKBShares)
|
||||
// Update share permission
|
||||
kbShares.PUT("/:share_id", orgHandler.UpdateSharePermission)
|
||||
// Remove share
|
||||
kbShares.DELETE("/:share_id", orgHandler.RemoveShare)
|
||||
}
|
||||
|
||||
// Shared knowledge bases route
|
||||
r.GET("/shared-knowledge-bases", orgHandler.ListSharedKnowledgeBases)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ const (
|
|||
LoggerContextKey ContextKey = "Logger"
|
||||
// UserContextKey is the context key for user information
|
||||
UserContextKey ContextKey = "User"
|
||||
// UserIDContextKey is the context key for user ID
|
||||
UserIDContextKey ContextKey = "UserID"
|
||||
)
|
||||
|
||||
// String returns the string representation of the context key
|
||||
|
|
|
|||
|
|
@ -12,10 +12,14 @@ type ChunkRepository interface {
|
|||
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
|
||||
// GetChunkByID gets a chunk by id
|
||||
GetChunkByID(ctx context.Context, tenantID uint64, id string) (*types.Chunk, error)
|
||||
// GetChunkByIDOnly gets a chunk by id without tenant filter (for permission resolution)
|
||||
GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// GetChunkBySeqID gets a chunk by seq_id
|
||||
GetChunkBySeqID(ctx context.Context, tenantID uint64, seqID int64) (*types.Chunk, error)
|
||||
// ListChunksByID lists chunks by ids
|
||||
ListChunksByID(ctx context.Context, tenantID uint64, ids []string) ([]*types.Chunk, error)
|
||||
// ListChunksByIDOnly lists chunks by ids without tenant filter (for shared KB resolution).
|
||||
ListChunksByIDOnly(ctx context.Context, ids []string) ([]*types.Chunk, error)
|
||||
// ListChunksBySeqID lists chunks by seq_ids
|
||||
ListChunksBySeqID(ctx context.Context, tenantID uint64, seqIDs []int64) ([]*types.Chunk, error)
|
||||
// ListChunksByKnowledgeID lists chunks by knowledge id
|
||||
|
|
@ -84,8 +88,10 @@ type ChunkRepository interface {
|
|||
type ChunkService interface {
|
||||
// CreateChunks creates chunks
|
||||
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
|
||||
// GetChunkByID gets a chunk by id
|
||||
// GetChunkByID gets a chunk by id (uses tenant from context)
|
||||
GetChunkByID(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// GetChunkByIDOnly gets a chunk by id without tenant filter (for permission resolution)
|
||||
GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error)
|
||||
// ListChunksByKnowledgeID lists chunks by knowledge id
|
||||
ListChunksByKnowledgeID(ctx context.Context, knowledgeID string) ([]*types.Chunk, error)
|
||||
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id
|
||||
|
|
|
|||
|
|
@ -42,10 +42,14 @@ type KnowledgeService interface {
|
|||
kbID string,
|
||||
payload *types.ManualKnowledgePayload,
|
||||
) (*types.Knowledge, error)
|
||||
// GetKnowledgeByID retrieves knowledge by ID.
|
||||
// GetKnowledgeByID retrieves knowledge by ID (uses tenant from context).
|
||||
GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeByIDOnly retrieves knowledge by ID without tenant filter (for permission resolution).
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeBatch retrieves a batch of knowledge by IDs.
|
||||
GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
|
||||
// GetKnowledgeBatchWithSharedAccess retrieves knowledge by IDs including items from shared KBs the user has access to.
|
||||
GetKnowledgeBatchWithSharedAccess(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
|
||||
// ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base.
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.
|
||||
|
|
@ -148,6 +152,8 @@ type KnowledgeService interface {
|
|||
type KnowledgeRepository interface {
|
||||
CreateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
|
||||
GetKnowledgeByID(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error)
|
||||
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination.
|
||||
// When tagID is non-empty, results are filtered by tag_id.
|
||||
|
|
@ -182,6 +188,8 @@ type KnowledgeRepository interface {
|
|||
// SearchKnowledge searches knowledge items by keyword across the tenant.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
SearchKnowledge(ctx context.Context, tenantID uint64, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (own + shared).
|
||||
SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
// ListIDsByTagID returns all knowledge IDs that have the specified tag ID.
|
||||
ListIDsByTagID(ctx context.Context, tenantID uint64, kbID, tagID string) ([]string, error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ type KnowledgeBaseService interface {
|
|||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error)
|
||||
|
||||
// GetKnowledgeBaseByIDOnly retrieves knowledge base by ID without tenant filter
|
||||
// Used for cross-tenant shared KB access where permission is checked elsewhere
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the knowledge base
|
||||
// Returns:
|
||||
// - Knowledge base object, if found
|
||||
// - Possible errors such as not existing, etc.
|
||||
GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error)
|
||||
|
||||
// ListKnowledgeBases lists all knowledge bases under the current tenant
|
||||
// Parameters:
|
||||
// - ctx: Context information, containing tenant information
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ type ModelService interface {
|
|||
DeleteModel(ctx context.Context, id string) error
|
||||
// GetEmbeddingModel gets an embedding model
|
||||
GetEmbeddingModel(ctx context.Context, modelId string) (embedding.Embedder, error)
|
||||
// GetEmbeddingModelForTenant gets an embedding model for a specific tenant (for cross-tenant sharing)
|
||||
GetEmbeddingModelForTenant(ctx context.Context, modelId string, tenantID uint64) (embedding.Embedder, error)
|
||||
// GetRerankModel gets a rerank model
|
||||
GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error)
|
||||
// GetChatModel gets a chat model
|
||||
|
|
|
|||
|
|
@ -0,0 +1,125 @@
|
|||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// OrganizationService defines the organization service interface
|
||||
type OrganizationService interface {
|
||||
// Organization CRUD
|
||||
CreateOrganization(ctx context.Context, userID string, tenantID uint64, req *types.CreateOrganizationRequest) (*types.Organization, error)
|
||||
GetOrganization(ctx context.Context, id string) (*types.Organization, error)
|
||||
GetOrganizationByInviteCode(ctx context.Context, inviteCode string) (*types.Organization, error)
|
||||
ListUserOrganizations(ctx context.Context, userID string) ([]*types.Organization, error)
|
||||
UpdateOrganization(ctx context.Context, id string, userID string, req *types.UpdateOrganizationRequest) (*types.Organization, error)
|
||||
DeleteOrganization(ctx context.Context, id string, userID string) error
|
||||
|
||||
// Member Management
|
||||
AddMember(ctx context.Context, orgID string, userID string, tenantID uint64, role types.OrgMemberRole) error
|
||||
RemoveMember(ctx context.Context, orgID string, memberUserID string, operatorUserID string) error
|
||||
UpdateMemberRole(ctx context.Context, orgID string, memberUserID string, role types.OrgMemberRole, operatorUserID string) error
|
||||
ListMembers(ctx context.Context, orgID string) ([]*types.OrganizationMember, error)
|
||||
GetMember(ctx context.Context, orgID string, userID string) (*types.OrganizationMember, error)
|
||||
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
ListJoinRequests(ctx context.Context, orgID string) ([]*types.OrganizationJoinRequest, error)
|
||||
CountPendingJoinRequests(ctx context.Context, orgID string) (int64, error)
|
||||
ReviewJoinRequest(ctx context.Context, orgID string, requestID string, approved bool, reviewerID string, message string, assignRole *types.OrgMemberRole) error
|
||||
|
||||
// Role Upgrade Requests (for existing members to request higher permissions)
|
||||
RequestRoleUpgrade(ctx context.Context, orgID string, userID string, tenantID uint64, requestedRole types.OrgMemberRole, message string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingUpgradeRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
||||
|
||||
// Permission Check
|
||||
IsOrgAdmin(ctx context.Context, orgID string, userID string) (bool, error)
|
||||
GetUserRoleInOrg(ctx context.Context, orgID string, userID string) (types.OrgMemberRole, error)
|
||||
}
|
||||
|
||||
// OrganizationRepository defines the organization repository interface
|
||||
type OrganizationRepository interface {
|
||||
// Organization CRUD
|
||||
Create(ctx context.Context, org *types.Organization) error
|
||||
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)
|
||||
Update(ctx context.Context, org *types.Organization) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// Member operations
|
||||
AddMember(ctx context.Context, member *types.OrganizationMember) error
|
||||
RemoveMember(ctx context.Context, orgID string, userID string) error
|
||||
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)
|
||||
CountMembers(ctx context.Context, orgID string) (int64, error)
|
||||
|
||||
// Invite code
|
||||
UpdateInviteCode(ctx context.Context, orgID string, inviteCode string, expiresAt *time.Time) error
|
||||
|
||||
// Join requests
|
||||
CreateJoinRequest(ctx context.Context, request *types.OrganizationJoinRequest) error
|
||||
GetJoinRequestByID(ctx context.Context, id string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingJoinRequest(ctx context.Context, orgID string, userID string) (*types.OrganizationJoinRequest, error)
|
||||
GetPendingRequestByType(ctx context.Context, orgID string, userID string, requestType types.JoinRequestType) (*types.OrganizationJoinRequest, error)
|
||||
ListJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) ([]*types.OrganizationJoinRequest, error)
|
||||
CountJoinRequests(ctx context.Context, orgID string, status types.JoinRequestStatus) (int64, error)
|
||||
UpdateJoinRequestStatus(ctx context.Context, id string, status types.JoinRequestStatus, reviewedBy string, reviewMessage string) error
|
||||
}
|
||||
|
||||
// KBShareService defines the knowledge base sharing service interface
|
||||
type KBShareService interface {
|
||||
// Share Management
|
||||
ShareKnowledgeBase(ctx context.Context, kbID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.KnowledgeBaseShare, error)
|
||||
UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string) error
|
||||
RemoveShare(ctx context.Context, shareID string, userID string) error
|
||||
|
||||
// Query
|
||||
ListSharesByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
|
||||
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
|
||||
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Permission Check
|
||||
CheckUserKBPermission(ctx context.Context, kbID string, userID string) (types.OrgMemberRole, bool, error)
|
||||
HasKBPermission(ctx context.Context, kbID string, userID string, requiredRole types.OrgMemberRole) (bool, error)
|
||||
|
||||
// Get source tenant for cross-tenant embedding
|
||||
GetKBSourceTenant(ctx context.Context, kbID string) (uint64, error)
|
||||
|
||||
// Count shares for knowledge bases
|
||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||
}
|
||||
|
||||
// KBShareRepository defines the knowledge base sharing repository interface
|
||||
type KBShareRepository interface {
|
||||
// CRUD
|
||||
Create(ctx context.Context, share *types.KnowledgeBaseShare) error
|
||||
GetByID(ctx context.Context, id string) (*types.KnowledgeBaseShare, error)
|
||||
GetByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
|
||||
Update(ctx context.Context, share *types.KnowledgeBaseShare) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
// DeleteByKnowledgeBaseID soft-deletes all shares for a knowledge base (e.g. when KB is deleted)
|
||||
DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error
|
||||
// DeleteByOrganizationID soft-deletes all shares for an organization (e.g. when the org is deleted)
|
||||
DeleteByOrganizationID(ctx context.Context, orgID string) error
|
||||
|
||||
// List
|
||||
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
|
||||
ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Query for user's accessible shared knowledge bases
|
||||
ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error)
|
||||
|
||||
// Count shares
|
||||
CountSharesByKnowledgeBaseID(ctx context.Context, kbID string) (int64, error)
|
||||
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
|
||||
}
|
||||
|
|
@ -36,6 +36,8 @@ type UserService interface {
|
|||
RevokeToken(ctx context.Context, token string) error
|
||||
// GetCurrentUser gets current user from context
|
||||
GetCurrentUser(ctx context.Context) (*types.User, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
// UserRepository defines the user repository interface
|
||||
|
|
@ -54,6 +56,8 @@ type UserRepository interface {
|
|||
DeleteUser(ctx context.Context, id string) error
|
||||
// ListUsers lists users with pagination
|
||||
ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error)
|
||||
// SearchUsers searches users by username or email
|
||||
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
|
||||
}
|
||||
|
||||
// AuthTokenRepository defines the auth token repository interface
|
||||
|
|
|
|||
|
|
@ -147,6 +147,12 @@ type ManualKnowledgePayload struct {
|
|||
TagID string `json:"tag_id"`
|
||||
}
|
||||
|
||||
// KnowledgeSearchScope defines a (tenant_id, knowledge_base_id) scope for knowledge search (e.g. own KBs + shared KBs).
|
||||
type KnowledgeSearchScope struct {
|
||||
TenantID uint64
|
||||
KBID string
|
||||
}
|
||||
|
||||
// NewManualKnowledgeMetadata creates a new ManualKnowledgeMetadata instance.
|
||||
func NewManualKnowledgeMetadata(content, status string, version int) *ManualKnowledgeMetadata {
|
||||
if version <= 0 {
|
||||
|
|
|
|||
|
|
@ -81,6 +81,8 @@ type KnowledgeBase struct {
|
|||
IsProcessing bool `yaml:"is_processing" json:"is_processing" gorm:"-"`
|
||||
// ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)
|
||||
ProcessingCount int64 `yaml:"processing_count" json:"processing_count" gorm:"-"`
|
||||
// ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)
|
||||
ShareCount int64 `yaml:"share_count" json:"share_count" gorm:"-"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseConfig represents the knowledge base configuration
|
||||
|
|
|
|||
|
|
@ -0,0 +1,373 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OrgMemberRole represents the role of an organization member
|
||||
type OrgMemberRole string
|
||||
|
||||
const (
|
||||
// OrgRoleAdmin has full control over the organization and shared knowledge bases
|
||||
OrgRoleAdmin OrgMemberRole = "admin"
|
||||
// OrgRoleEditor can edit shared knowledge base content but cannot manage settings
|
||||
OrgRoleEditor OrgMemberRole = "editor"
|
||||
// OrgRoleViewer can only view and search shared knowledge bases
|
||||
OrgRoleViewer OrgMemberRole = "viewer"
|
||||
)
|
||||
|
||||
// IsValid checks if the role is valid
|
||||
func (r OrgMemberRole) IsValid() bool {
|
||||
switch r {
|
||||
case OrgRoleAdmin, OrgRoleEditor, OrgRoleViewer:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// HasPermission checks if this role has at least the required permission level
|
||||
func (r OrgMemberRole) HasPermission(required OrgMemberRole) bool {
|
||||
roleLevel := map[OrgMemberRole]int{
|
||||
OrgRoleAdmin: 3,
|
||||
OrgRoleEditor: 2,
|
||||
OrgRoleViewer: 1,
|
||||
}
|
||||
return roleLevel[r] >= roleLevel[required]
|
||||
}
|
||||
|
||||
// Organization represents a collaboration organization for cross-tenant sharing
|
||||
type Organization struct {
|
||||
// Unique identifier of the organization
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Name of the organization
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Description of the organization
|
||||
Description string `json:"description" gorm:"type:text"`
|
||||
// Avatar URL for display in list and settings
|
||||
Avatar string `json:"avatar" gorm:"type:varchar(512)"`
|
||||
// User ID of the organization owner
|
||||
OwnerID string `json:"owner_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Unique invitation code for joining the organization
|
||||
InviteCode string `json:"invite_code" gorm:"type:varchar(32);uniqueIndex"`
|
||||
// When the current invite code expires; nil means no expiry
|
||||
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at" gorm:"type:timestamp with time zone"`
|
||||
// Invite link validity in days: 0=never, 1/7/30
|
||||
InviteCodeValidityDays int `json:"invite_code_validity_days" gorm:"default:7"`
|
||||
// Whether joining requires admin approval
|
||||
RequireApproval bool `json:"require_approval" gorm:"default:false"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Deletion time (soft delete)
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Owner *User `json:"owner,omitempty" gorm:"foreignKey:OwnerID"`
|
||||
Members []OrganizationMember `json:"members,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
Shares []KnowledgeBaseShare `json:"shares,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (Organization) TableName() string {
|
||||
return "organizations"
|
||||
}
|
||||
|
||||
// OrganizationMember represents a member of an organization
|
||||
type OrganizationMember struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Organization ID
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID of the member
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Tenant ID that the member belongs to
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
// Role in the organization (admin/editor/viewer)
|
||||
Role OrgMemberRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (OrganizationMember) TableName() string {
|
||||
return "organization_members"
|
||||
}
|
||||
|
||||
// JoinRequestStatus represents the status of a join request
|
||||
type JoinRequestStatus string
|
||||
|
||||
const (
|
||||
JoinRequestStatusPending JoinRequestStatus = "pending"
|
||||
JoinRequestStatusApproved JoinRequestStatus = "approved"
|
||||
JoinRequestStatusRejected JoinRequestStatus = "rejected"
|
||||
)
|
||||
|
||||
// JoinRequestType represents the type of a join request
|
||||
type JoinRequestType string
|
||||
|
||||
const (
|
||||
// JoinRequestTypeJoin is for new member join requests
|
||||
JoinRequestTypeJoin JoinRequestType = "join"
|
||||
// JoinRequestTypeUpgrade is for role upgrade requests from existing members
|
||||
JoinRequestTypeUpgrade JoinRequestType = "upgrade"
|
||||
)
|
||||
|
||||
// OrganizationJoinRequest represents a request to join an organization or upgrade role
|
||||
type OrganizationJoinRequest struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Organization ID
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID of the requester
|
||||
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Tenant ID of the requester
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null"`
|
||||
// Type of request: 'join' for new member, 'upgrade' for role upgrade
|
||||
RequestType JoinRequestType `json:"request_type" gorm:"type:varchar(32);not null;default:'join';index"`
|
||||
// Previous role before upgrade (only for upgrade requests)
|
||||
PrevRole OrgMemberRole `json:"prev_role" gorm:"column:prev_role;type:varchar(32)"`
|
||||
// Role requested by the applicant (admin/editor/viewer)
|
||||
RequestedRole OrgMemberRole `json:"requested_role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Status of the request
|
||||
Status JoinRequestStatus `json:"status" gorm:"type:varchar(32);not null;default:'pending';index"`
|
||||
// Optional message from the requester
|
||||
Message string `json:"message" gorm:"type:text"`
|
||||
// User ID of the admin who reviewed the request
|
||||
ReviewedBy string `json:"reviewed_by" gorm:"type:varchar(36)"`
|
||||
// Time when the request was reviewed
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
// Optional message from the reviewer
|
||||
ReviewMessage string `json:"review_message" gorm:"type:text"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
User *User `json:"user,omitempty" gorm:"foreignKey:UserID"`
|
||||
Reviewer *User `json:"reviewer,omitempty" gorm:"foreignKey:ReviewedBy"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (OrganizationJoinRequest) TableName() string {
|
||||
return "organization_join_requests"
|
||||
}
|
||||
|
||||
// KnowledgeBaseShare represents a sharing record of a knowledge base to an organization
|
||||
type KnowledgeBaseShare struct {
|
||||
// Unique identifier
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Knowledge base ID being shared
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);not null;index"`
|
||||
// Organization ID receiving the share
|
||||
OrganizationID string `json:"organization_id" gorm:"type:varchar(36);not null;index"`
|
||||
// User ID who shared the knowledge base
|
||||
SharedByUserID string `json:"shared_by_user_id" gorm:"type:varchar(36);not null"`
|
||||
// Original tenant ID of the knowledge base (for cross-tenant embedding model access)
|
||||
SourceTenantID uint64 `json:"source_tenant_id" gorm:"not null;index"`
|
||||
// Permission level (admin/editor/viewer)
|
||||
Permission OrgMemberRole `json:"permission" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
// Creation time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Last updated time
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Deletion time (soft delete)
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
|
||||
// Associations (not stored in database)
|
||||
KnowledgeBase *KnowledgeBase `json:"knowledge_base,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
|
||||
Organization *Organization `json:"organization,omitempty" gorm:"foreignKey:OrganizationID"`
|
||||
}
|
||||
|
||||
// TableName returns the table name for GORM
|
||||
func (KnowledgeBaseShare) TableName() string {
|
||||
return "kb_shares"
|
||||
}
|
||||
|
||||
// SharedKnowledgeBaseInfo represents a shared knowledge base with additional sharing info
|
||||
type SharedKnowledgeBaseInfo struct {
|
||||
KnowledgeBase *KnowledgeBase `json:"knowledge_base"`
|
||||
ShareID string `json:"share_id"`
|
||||
OrganizationID string `json:"organization_id"`
|
||||
OrgName string `json:"org_name"`
|
||||
Permission OrgMemberRole `json:"permission"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
SharedAt time.Time `json:"shared_at"`
|
||||
}
|
||||
|
||||
// ----------------------
|
||||
// Request/Response Types
|
||||
// ----------------------
|
||||
|
||||
// CreateOrganizationRequest represents a request to create an organization
|
||||
type CreateOrganizationRequest struct {
|
||||
Name string `json:"name" binding:"required,min=1,max=255"`
|
||||
Description string `json:"description" binding:"max=1000"`
|
||||
Avatar string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
||||
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // optional: 0=never, 1, 7, 30; default 7
|
||||
}
|
||||
|
||||
// UpdateOrganizationRequest represents a request to update an organization
|
||||
type UpdateOrganizationRequest struct {
|
||||
Name *string `json:"name" binding:"omitempty,min=1,max=255"`
|
||||
Description *string `json:"description" binding:"omitempty,max=1000"`
|
||||
Avatar *string `json:"avatar" binding:"omitempty,max=512"` // optional avatar URL
|
||||
RequireApproval *bool `json:"require_approval"`
|
||||
InviteCodeValidityDays *int `json:"invite_code_validity_days"` // 0=never, 1, 7, 30
|
||||
}
|
||||
|
||||
// AddMemberRequest represents a request to add a member to an organization
|
||||
type AddMemberRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Role OrgMemberRole `json:"role" binding:"required"`
|
||||
}
|
||||
|
||||
// UpdateMemberRoleRequest represents a request to update a member's role
|
||||
type UpdateMemberRoleRequest struct {
|
||||
Role OrgMemberRole `json:"role" binding:"required"`
|
||||
}
|
||||
|
||||
// JoinOrganizationRequest represents a request to join an organization via invite code
|
||||
type JoinOrganizationRequest struct {
|
||||
InviteCode string `json:"invite_code" binding:"required,min=8,max=32"`
|
||||
}
|
||||
|
||||
// SubmitJoinRequestRequest represents a request to submit a join request for approval
|
||||
type SubmitJoinRequestRequest struct {
|
||||
InviteCode string `json:"invite_code" binding:"required,min=8,max=32"`
|
||||
Message string `json:"message" binding:"max=500"`
|
||||
Role OrgMemberRole `json:"role"` // Optional: role the applicant requests (admin/editor/viewer); default viewer
|
||||
}
|
||||
|
||||
// ReviewJoinRequestRequest represents a request to review a join request
|
||||
type ReviewJoinRequestRequest struct {
|
||||
Approved bool `json:"approved"`
|
||||
Message string `json:"message" binding:"max=500"`
|
||||
Role OrgMemberRole `json:"role"` // Optional: role to assign when approving; overrides applicant's requested role
|
||||
}
|
||||
|
||||
// RequestRoleUpgradeRequest represents a request to upgrade role in an organization
|
||||
type RequestRoleUpgradeRequest struct {
|
||||
RequestedRole OrgMemberRole `json:"requested_role" binding:"required"` // The role user wants to upgrade to
|
||||
Message string `json:"message" binding:"max=500"` // Optional message explaining the reason
|
||||
}
|
||||
|
||||
// InviteMemberRequest represents a request to directly invite a user to organization
|
||||
type InviteMemberRequest struct {
|
||||
UserID string `json:"user_id" binding:"required"` // User ID to invite
|
||||
Role OrgMemberRole `json:"role" binding:"required"` // Role to assign: admin/editor/viewer
|
||||
}
|
||||
|
||||
// ShareKnowledgeBaseRequest represents a request to share a knowledge base
|
||||
type ShareKnowledgeBaseRequest struct {
|
||||
OrganizationID string `json:"organization_id" binding:"required"`
|
||||
Permission OrgMemberRole `json:"permission" binding:"required"`
|
||||
}
|
||||
|
||||
// UpdateSharePermissionRequest represents a request to update share permission
|
||||
type UpdateSharePermissionRequest struct {
|
||||
Permission OrgMemberRole `json:"permission" binding:"required"`
|
||||
}
|
||||
|
||||
// OrganizationResponse represents an organization in API responses
|
||||
type OrganizationResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
InviteCode string `json:"invite_code,omitempty"`
|
||||
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
|
||||
InviteCodeValidityDays int `json:"invite_code_validity_days"`
|
||||
RequireApproval bool `json:"require_approval"`
|
||||
MemberCount int `json:"member_count"`
|
||||
ShareCount int `json:"share_count"` // 共享到该组织的知识库数量
|
||||
PendingJoinRequestCount int `json:"pending_join_request_count"` // 待审批加入申请数(仅管理员可见)
|
||||
IsOwner bool `json:"is_owner"`
|
||||
MyRole string `json:"my_role,omitempty"`
|
||||
HasPendingUpgrade bool `json:"has_pending_upgrade"` // 当前用户是否有待处理的权限升级申请
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// OrganizationMemberResponse represents a member in API responses
|
||||
type OrganizationMemberResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
}
|
||||
|
||||
// KnowledgeBaseShareResponse represents a share record in API responses
|
||||
type KnowledgeBaseShareResponse struct {
|
||||
ID string `json:"id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
KnowledgeBaseName string `json:"knowledge_base_name"`
|
||||
KnowledgeBaseType string `json:"knowledge_base_type"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
OrganizationID string `json:"organization_id"`
|
||||
OrganizationName string `json:"organization_name"`
|
||||
SharedByUserID string `json:"shared_by_user_id"`
|
||||
SharedByUsername string `json:"shared_by_username"`
|
||||
SourceTenantID uint64 `json:"source_tenant_id"`
|
||||
Permission string `json:"permission"` // Share permission (what the space was granted: viewer/editor)
|
||||
MyRoleInOrg string `json:"my_role_in_org"` // Current user's role in this organization (admin/editor/viewer)
|
||||
MyPermission string `json:"my_permission"` // Effective permission for current user = min(Permission, MyRoleInOrg)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
RequireApproval bool `json:"require_approval"`
|
||||
}
|
||||
|
||||
// ListOrganizationsResponse represents the response for listing organizations
|
||||
type ListOrganizationsResponse struct {
|
||||
Organizations []OrganizationResponse `json:"organizations"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// JoinRequestResponse represents a join request in API responses
|
||||
type JoinRequestResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Message string `json:"message"`
|
||||
RequestType string `json:"request_type"` // 'join' or 'upgrade'
|
||||
PrevRole string `json:"prev_role"` // Previous role (only for upgrade requests)
|
||||
RequestedRole string `json:"requested_role"` // Role the applicant requested (admin/editor/viewer)
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
|
||||
}
|
||||
|
||||
// ListJoinRequestsResponse represents the response for listing join requests
|
||||
type ListJoinRequestsResponse struct {
|
||||
Requests []JoinRequestResponse `json:"requests"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// ListMembersResponse represents the response for listing members
|
||||
type ListMembersResponse struct {
|
||||
Members []OrganizationMemberResponse `json:"members"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
// ListSharesResponse represents the response for listing shares
|
||||
type ListSharesResponse struct {
|
||||
Shares []KnowledgeBaseShareResponse `json:"shares"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
|
@ -22,6 +22,9 @@ type SearchTarget struct {
|
|||
Type SearchTargetType `json:"type"`
|
||||
// KnowledgeBaseID is the ID of the knowledge base to search
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
// TenantID is the tenant ID that owns this knowledge base
|
||||
// Required for cross-tenant shared KB queries
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
// KnowledgeIDs is the list of specific knowledge IDs to search within the knowledge base
|
||||
// Only used when Type is SearchTargetTypeKnowledge
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
|
|
@ -43,6 +46,38 @@ func (st SearchTargets) GetAllKnowledgeBaseIDs() []string {
|
|||
return result
|
||||
}
|
||||
|
||||
// GetKBTenantMap returns a map from knowledge base ID to tenant ID
|
||||
func (st SearchTargets) GetKBTenantMap() map[string]uint64 {
|
||||
result := make(map[string]uint64)
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID != "" {
|
||||
result[t.KnowledgeBaseID] = t.TenantID
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetTenantIDForKB returns the tenant ID for a given knowledge base ID
|
||||
// Returns 0 if not found
|
||||
func (st SearchTargets) GetTenantIDForKB(kbID string) uint64 {
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID == kbID {
|
||||
return t.TenantID
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ContainsKB checks if the search targets contain a given knowledge base ID
|
||||
func (st SearchTargets) ContainsKB(kbID string) bool {
|
||||
for _, t := range st {
|
||||
if t.KnowledgeBaseID == kbID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SearchResult represents the search result
|
||||
type SearchResult struct {
|
||||
// ID
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
-- Migration: 000011_organizations (down, merged 000011–000017)
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000011] Rolling back organization tables...'; END $$;
|
||||
|
||||
DROP TABLE IF EXISTS organization_join_requests;
|
||||
DROP TABLE IF EXISTS kb_shares;
|
||||
DROP TABLE IF EXISTS organization_members;
|
||||
DROP TABLE IF EXISTS organizations;
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000011] Rollback completed successfully!'; END $$;
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
-- Migration: 000011_organizations (merged 000011–000017)
|
||||
-- Description: Organization tables, approval, invite expiry, join requests, avatar
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000011] Starting organization tables setup...'; END $$;
|
||||
|
||||
-- Create organizations table
|
||||
CREATE TABLE IF NOT EXISTS organizations (
|
||||
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
owner_id VARCHAR(36) NOT NULL,
|
||||
invite_code VARCHAR(32),
|
||||
require_approval BOOLEAN DEFAULT FALSE,
|
||||
invite_code_expires_at TIMESTAMP WITH TIME ZONE,
|
||||
invite_code_validity_days SMALLINT NOT NULL DEFAULT 7,
|
||||
avatar VARCHAR(512) DEFAULT '',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_organizations_invite_code ON organizations(invite_code) WHERE invite_code IS NOT NULL AND deleted_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_organizations_owner_id ON organizations(owner_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_organizations_deleted_at ON organizations(deleted_at);
|
||||
|
||||
COMMENT ON TABLE organizations IS 'Organizations for cross-tenant collaboration';
|
||||
COMMENT ON COLUMN organizations.owner_id IS 'User ID of the organization owner';
|
||||
COMMENT ON COLUMN organizations.invite_code IS 'Unique invitation code for joining the organization';
|
||||
COMMENT ON COLUMN organizations.require_approval IS 'Whether joining this organization requires admin approval';
|
||||
COMMENT ON COLUMN organizations.invite_code_expires_at IS 'When the current invite code expires; NULL means no expiry (legacy)';
|
||||
COMMENT ON COLUMN organizations.invite_code_validity_days IS 'Invite link validity in days: 0=never expire, 1/7/30 days';
|
||||
|
||||
-- Create organization_members table
|
||||
CREATE TABLE IF NOT EXISTS organization_members (
|
||||
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_members_org_user ON organization_members(organization_id, user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_members_user_id ON organization_members(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_members_tenant_id ON organization_members(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_members_role ON organization_members(role);
|
||||
|
||||
COMMENT ON TABLE organization_members IS 'Members of organizations with their roles';
|
||||
COMMENT ON COLUMN organization_members.role IS 'Member role: admin, editor, or viewer';
|
||||
COMMENT ON COLUMN organization_members.tenant_id IS 'The tenant ID that the member belongs to';
|
||||
|
||||
-- Create kb_shares table (knowledge base sharing)
|
||||
CREATE TABLE IF NOT EXISTS kb_shares (
|
||||
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
knowledge_base_id VARCHAR(36) NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
|
||||
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
shared_by_user_id VARCHAR(36) NOT NULL,
|
||||
source_tenant_id INTEGER NOT NULL,
|
||||
permission VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_kb_shares_kb_org ON kb_shares(knowledge_base_id, organization_id) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_kb_shares_kb_id ON kb_shares(knowledge_base_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_kb_shares_org_id ON kb_shares(organization_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_kb_shares_source_tenant ON kb_shares(source_tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_kb_shares_deleted_at ON kb_shares(deleted_at);
|
||||
|
||||
COMMENT ON TABLE kb_shares IS 'Knowledge base sharing records to organizations';
|
||||
COMMENT ON COLUMN kb_shares.source_tenant_id IS 'Original tenant ID of the knowledge base for cross-tenant embedding model access';
|
||||
COMMENT ON COLUMN kb_shares.permission IS 'Access permission level: admin, editor, or viewer';
|
||||
|
||||
-- Create organization_join_requests table
|
||||
CREATE TABLE IF NOT EXISTS organization_join_requests (
|
||||
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
organization_id VARCHAR(36) NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
requested_role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||
request_type VARCHAR(32) NOT NULL DEFAULT 'join',
|
||||
prev_role VARCHAR(32),
|
||||
message TEXT,
|
||||
reviewed_by VARCHAR(36),
|
||||
reviewed_at TIMESTAMP WITH TIME ZONE,
|
||||
review_message TEXT,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_org_join_requests_org_user_pending ON organization_join_requests(organization_id, user_id) WHERE status = 'pending';
|
||||
CREATE INDEX IF NOT EXISTS idx_org_join_requests_org_id ON organization_join_requests(organization_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_join_requests_user_id ON organization_join_requests(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_join_requests_status ON organization_join_requests(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_org_join_requests_type ON organization_join_requests(request_type);
|
||||
|
||||
COMMENT ON TABLE organization_join_requests IS 'Join requests for organizations that require approval';
|
||||
COMMENT ON COLUMN organization_join_requests.status IS 'Request status: pending, approved, rejected';
|
||||
COMMENT ON COLUMN organization_join_requests.requested_role IS 'Role requested by the applicant: admin, editor, viewer';
|
||||
COMMENT ON COLUMN organization_join_requests.request_type IS 'join for new member, upgrade for role upgrade';
|
||||
COMMENT ON COLUMN organization_join_requests.message IS 'Optional message from the requester';
|
||||
COMMENT ON COLUMN organization_join_requests.reviewed_by IS 'User ID of the admin who reviewed the request';
|
||||
COMMENT ON COLUMN organization_join_requests.review_message IS 'Optional message from the reviewer';
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000011] Organization tables setup completed successfully!'; END $$;
|
||||
Loading…
Reference in New Issue