From 448fbcdaff7d6257409335b399d2cafe607ac594 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 24 Nov 2026 18:16:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(org):=20=E7=BB=84=E7=BB=87=E6=9E=B6?= =?UTF-8?q?=E6=9E=84=E6=96=B0=E5=A2=9E=E3=80=8C=E6=94=B6=E7=BC=96=E5=88=B0?= =?UTF-8?q?=E6=9C=AC=E7=A9=BA=E9=97=B4=E3=80=8D,=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E6=88=90=E5=91=98=E7=99=BB=E5=BD=95=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E8=90=BD=E7=82=B9=20=E5=91=98=E5=B7=A5=E9=A6=96?= =?UTF-8?q?=E7=99=BB=E8=87=AA=E5=8A=A8=E5=BC=80=E9=80=9A=E4=B8=AA=E4=BA=BA?= =?UTF-8?q?=E7=A9=BA=E9=97=B4(create=5Fpersonal=20=E9=BB=98=E8=AE=A4)?= =?UTF-8?q?=E5=90=8E,=E5=BD=92=E5=B1=9E=E7=A9=BA=E9=97=B4(users.tenant=5Fi?= =?UTF-8?q?d)=20=E4=B8=8E=E3=80=8C=E6=9C=80=E8=BF=91=E6=B4=BB=E8=B7=83?= =?UTF-8?q?=E7=A7=9F=E6=88=B7=E3=80=8D=E5=81=8F=E5=A5=BD=E5=81=9C=E5=9C=A8?= =?UTF-8?q?=E4=B8=AA=E4=BA=BA=E7=A9=BA=E9=97=B4,=E7=99=BB=E5=BD=95?= =?UTF-8?q?=E5=90=8E=E7=9C=8B=E5=88=B0=E7=9A=84=E6=98=AF=E4=B8=AA=E4=BA=BA?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E9=87=8C=E9=82=A3=E4=BB=BD=E7=A9=BA=E7=9A=84?= =?UTF-8?q?=E7=BB=84=E7=BB=87=20=E6=9E=B6=E6=9E=84/=E5=9F=B9=E8=AE=AD?= =?UTF-8?q?=E6=95=B0=E6=8D=AE,=E6=A8=A1=E6=9D=BF=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E4=B9=9F=E6=B2=A1=E6=9C=89=E9=83=A8=E9=97=A8=E4=B8=8B=E6=8B=89?= =?UTF-8?q?=E3=80=82=E7=A9=BA=E9=97=B4=20Owner=20=E7=8E=B0=E5=8F=AF?= =?UTF-8?q?=E4=B8=80=E9=94=AE=E6=94=B6=E7=BC=96:=201.=20GET=20/org/employe?= =?UTF-8?q?es/adoptable=20=E6=94=B6=E7=BC=96=E9=A2=84=E8=A7=88:=E5=BD=92?= =?UTF-8?q?=E5=B1=9E=E7=A9=BA=E9=97=B4=E4=B8=8D=E5=9C=A8=E6=9C=AC=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E7=9A=84=E6=B4=BB=E8=B7=83=E6=88=90=E5=91=98=20=20=20?= =?UTF-8?q?=20(COALESCE=20=E5=85=9C=E5=BA=95=20NULL=20=E5=BD=92=E5=B1=9E,?= =?UTF-8?q?=E8=81=94=E6=9F=A5=E5=90=8D=E5=86=8C=E6=A0=87=E8=AE=B0=E4=B8=8E?= =?UTF-8?q?=E5=BD=92=E5=B1=9E=E7=A9=BA=E9=97=B4=E5=90=8D=E4=BE=9B=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4);=202.=20POST=20/org/employees/adopt-home=20=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E6=94=B6=E7=BC=96:=E9=80=90=E6=9D=A1=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=E4=B8=8D=E6=95=B4=E6=89=B9=E5=A4=B1=E8=B4=A5,?= =?UTF-8?q?=E9=9D=9E=E6=9C=AC=E7=A9=BA=E9=97=B4=20=20=20=20=E6=88=90?= =?UTF-8?q?=E5=91=98/=E5=81=9C=E7=94=A8/=E8=B7=A8=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7/=E5=B7=B2=E5=BD=92=E5=B1=9E=E6=9C=AC?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E9=80=90=E6=9D=A1=E8=B7=B3=E8=BF=87=E5=B9=B6?= =?UTF-8?q?=E5=9B=9E=E4=BC=A0=E5=8E=9F=E5=9B=A0;=E5=BD=92=E5=B1=9E?= =?UTF-8?q?=E6=8C=87=E9=92=88=E4=B8=8E=E6=9C=80=E8=BF=91=20=20=20=20?= =?UTF-8?q?=E6=B4=BB=E8=B7=83=E7=A7=9F=E6=88=B7=E5=81=8F=E5=A5=BD=E4=B8=80?= =?UTF-8?q?=E8=B5=B7=E6=94=B9=E6=8C=87=E6=9C=AC=E7=A9=BA=E9=97=B4(?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=B7=AF=E5=BE=84=E4=BC=98=E5=85=88=E8=AF=BB?= =?UTF-8?q?=E5=81=8F=E5=A5=BD,=E5=8F=AA=E6=94=B9=E5=BD=92=E5=B1=9E?= =?UTF-8?q?=E4=BC=9A=E8=A2=AB=E6=97=A7=E5=81=8F=E5=A5=BD=20=20=20=20?= =?UTF-8?q?=E6=8B=89=E5=9B=9E),=E6=88=90=E5=91=98=E5=85=B3=E7=B3=BB/?= =?UTF-8?q?=E8=A7=92=E8=89=B2/=E4=B8=AA=E4=BA=BA=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E4=B8=8D=E5=8A=A8,=E5=8F=AF=E7=BB=8F?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E5=88=87=E6=8D=A2=E5=99=A8=E6=94=B9=E5=9B=9E?= =?UTF-8?q?,=E9=9D=9E=E7=A0=B4=E5=9D=8F=E6=80=A7;=203.=20=E6=94=B6?= =?UTF-8?q?=E7=BC=96=E6=88=90=E5=8A=9F=E8=80=85=E8=A1=A5=E8=B7=91=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=85=A5=E5=86=8C(EnsureEmployeesForUsers=20=E4=BB=85?= =?UTF-8?q?=E8=A1=A5=E7=A9=BA=E5=B9=82=E7=AD=89),=20=20=20=20=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E9=83=A8=E9=97=A8=E8=87=AA=E5=8A=A8=E5=8C=B9=E9=85=8D?= =?UTF-8?q?=E8=BF=9B=E5=90=8D=E5=86=8C;=204.=20=E5=8D=95=E6=9D=A1=20rbac.m?= =?UTF-8?q?ember=5Fhome=5Fadopted=20=E5=AE=A1=E8=AE=A1(best-effort);?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=20g.Owner()=20=E9=99=90=E5=AE=9A,=20=20=20?= =?UTF-8?q?=20=E4=B8=8E=E6=88=90=E5=91=98=E6=89=B9=E9=87=8F=E5=AF=BC?= =?UTF-8?q?=E5=85=A5/Casdoor=20=E5=90=8C=E6=AD=A5=E5=90=8C=E6=9D=83?= =?UTF-8?q?=E9=99=90=E7=BA=A7=E5=88=AB;=205.=20=E6=94=B6=E7=BC=96=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E5=8F=AA=E5=BC=95=20repository=20=E5=B1=82(UserReposi?= =?UTF-8?q?tory/TenantMemberRepository),=20=20=20=20=E9=81=BF=E5=BC=80=20t?= =?UTF-8?q?enantMemberService=E2=86=92OrgCenterService=E2=86=92userService?= =?UTF-8?q?=E2=86=92memberService=20=20=20=20=E7=9A=84=20DI=20=E7=8E=AF;?= =?UTF-8?q?=206.=20=E5=89=8D=E7=AB=AF=E7=BB=84=E7=BB=87=E6=9E=B6=E6=9E=84?= =?UTF-8?q?=E9=A1=B5=E6=96=B0=E5=A2=9E=E3=80=8C=E6=94=B6=E7=BC=96=E5=88=B0?= =?UTF-8?q?=E6=9C=AC=E7=A9=BA=E9=97=B4=E3=80=8D=E5=85=A5=E5=8F=A3(?= =?UTF-8?q?=E4=BB=85=20hasRole('owner')=20=E5=8F=AF=E8=A7=81)+=20=20=20=20?= =?UTF-8?q?=E9=A2=84=E8=A7=88=E7=A1=AE=E8=AE=A4=E5=BC=B9=E7=AA=97(?= =?UTF-8?q?=E4=B8=8E=20OA=20=E5=90=8C=E6=AD=A5=E5=BC=B9=E7=AA=97=E5=90=8C?= =?UTF-8?q?=E4=B8=A4=E6=AE=B5=E5=BC=8F=E4=BA=A4=E4=BA=92);=E9=A1=BA?= =?UTF-8?q?=E6=89=8B=E8=A1=A5=E9=BD=90=20=20=20=20OrgEmployee.wecom=5Fuser?= =?UTF-8?q?id=20=E7=BC=BA=E5=A4=B1=E7=9A=84=E5=AD=98=E9=87=8F=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=BC=BA=E5=8F=A3(type-check=20=E9=98=BB=E6=96=AD?= =?UTF-8?q?=E9=A1=B9)=E3=80=82=20=E6=B5=8B=E8=AF=95:=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=B1=82=E6=96=B0=E5=A2=9E=E6=94=B6=E7=BC=96=E8=90=BD=E7=82=B9?= =?UTF-8?q?+=E5=81=8F=E5=A5=BD/=E5=85=AD=E7=B1=BB=E8=B7=B3=E8=BF=87/?= =?UTF-8?q?=E5=AE=88=E5=8D=AB=203=20=E4=BE=8B;=E4=BB=93=E5=BA=93=E5=B1=82?= =?UTF-8?q?=20sqlite=20=E7=94=A8=E4=BE=8B=E8=A6=86=E7=9B=96=20NULL=20?= =?UTF-8?q?=E5=BD=92=E5=B1=9E=E5=85=9C=E5=BA=95=E4=B8=8E=E5=81=9C=E7=94=A8?= =?UTF-8?q?/=E5=B7=B2=E5=BD=92=E5=B1=9E=E6=8E=92=E9=99=A4;=E6=97=A2?= =?UTF-8?q?=E6=9C=89=20org/member/casdoor/=E5=9F=B9=E8=AE=AD=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E7=94=A8=E4=BE=8B=E6=97=A0=E5=9B=9E=E5=BD=92=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/api/org-center/index.ts | 39 ++++ frontend/src/views/org-center/OrgCenter.vue | 103 ++++++++++ internal/application/repository/orgcenter.go | 25 +++ .../orgcenter_adoptable_users_test.go | 104 ++++++++++ internal/application/service/orgcenter.go | 148 +++++++++++++- .../service/orgcenter_adopt_test.go | 185 ++++++++++++++++++ .../service/orgcenter_import_backfill_test.go | 4 +- .../service/tenant_member_sync_test.go | 8 +- internal/handler/orgcenter/orgcenter.go | 68 ++++++- internal/router/routes_org.go | 6 + internal/types/audit_log.go | 7 + internal/types/interfaces/orgcenter.go | 8 + internal/types/orgcenter.go | 82 +++++--- 13 files changed, 750 insertions(+), 37 deletions(-) create mode 100644 internal/application/repository/orgcenter_adoptable_users_test.go create mode 100644 internal/application/service/orgcenter_adopt_test.go diff --git a/frontend/src/api/org-center/index.ts b/frontend/src/api/org-center/index.ts index 4156aeb..a84259b 100644 --- a/frontend/src/api/org-center/index.ts +++ b/frontend/src/api/org-center/index.ts @@ -43,6 +43,8 @@ export interface OrgEmployee { post: string lecturer_rate: number status: string + /** 企微账号(OA 同步/绑定维护;列表 Select org_employees.* 随行返回)。 */ + wecom_userid?: string /** 联查展示字段:用户姓名/部门名称/指定 module_key 的绑定角色 */ user_name?: string dept_name?: string @@ -137,6 +139,43 @@ export const previewOrgWecomSync = () => export const applyOrgWecomSync = () => post<{ success: boolean; data: WecomSyncSummary }>(`${base}/employees/wecom-userid-sync/apply`) +// ---- 归属空间收编(登录默认落点;后端 Owner 限定) ---- +// 员工首登自动开通个人空间后,归属指针(users.tenant_id)停在个人空间,登录后 +// 看到的组织架构/培训是个人空间那份空数据;收编把默认落点改回本空间, +// 成员关系与个人空间数据不变(可经空间切换器改回,非破坏性)。 + +/** 可收编成员:归属空间不在本空间的活跃成员。 */ +export interface OrgAdoptableUser { + id: string + username: string + display_name: string + email: string + home_tenant_id: number + home_tenant_name: string + in_roster: boolean +} + +/** 单条收编跳过记录(非本空间成员/停用/跨空间账号等,原因逐条回传)。 */ +export interface OrgAdoptSkip { + user_id: string + username: string + display_name: string + reason: string +} + +export interface OrgAdoptResult { + adopted: number + skipped: OrgAdoptSkip[] +} + +/** 收编预览:归属空间不在本空间的活跃成员列表。 */ +export const listAdoptableUsers = () => + get<{ success: boolean; data: OrgAdoptableUser[] }>(`${base}/employees/adoptable`) + +/** 批量收编:把成员的归属空间(登录默认落点)改为本空间。 */ +export const adoptHomeTenant = (userIds: string[]) => + post<{ success: boolean; data: OrgAdoptResult }>(`${base}/employees/adopt-home`, { user_ids: userIds }) + // ---- 模块角色绑定 ---- export const listModuleMembers = (moduleKey: OrgModuleKey) => diff --git a/frontend/src/views/org-center/OrgCenter.vue b/frontend/src/views/org-center/OrgCenter.vue index de25a84..f0e1cd8 100644 --- a/frontend/src/views/org-center/OrgCenter.vue +++ b/frontend/src/views/org-center/OrgCenter.vue @@ -57,6 +57,9 @@ > 从OA同步企微账号 + + 收编到本空间 从平台用户添加 批量导入 @@ -242,6 +245,44 @@ 保存 + + + +
+ 名单为「归属空间不在本空间」的活跃成员(首次登录自动开通个人空间后,登录会落进个人空间,看不到本空间维护的组织架构与培训数据)。 + 收编后其默认登录空间改为本空间,下次登录起直接进入本空间;成员关系、角色与个人空间数据均不变,成员仍可随时用左下角空间切换器改回。 +
+ +
@@ -249,9 +290,11 @@ import { computed, onMounted, ref, watch } from 'vue' import { MessagePlugin } from 'tdesign-vue-next' import { + adoptHomeTenant, applyOrgWecomSync, deleteDept, importEmployees, + listAdoptableUsers, listDepts, listEmployees, listPlatformUsers, @@ -261,6 +304,7 @@ import { updateEmployee, updateOrgEmployeeRoles, updateOrgEmployeeWecomUserid, + type OrgAdoptableUser, type OrgDept, type OrgEmployee, type OrgPlatformUser, @@ -371,6 +415,61 @@ const onApplySync = async () => { } } +// ---- 收编到本空间(归属空间=登录默认落点;后端 Owner 限定) ---- + +// 仅空间 Owner 可见(与后端 g.Owner() 路由口径对齐;localStorage 只是渲染参考, +// 实际权限以服务端为准,越权点击会收到 403)。 +const canAdopt = computed(() => authStore.hasRole('owner')) +const adoptVisible = ref(false) +const adoptLoaded = ref(false) +const adopting = ref(false) +const adoptList = ref([]) + +const adoptColumns = [ + { colKey: 'username', title: '工号', width: 100 }, + { colKey: 'display_name', title: '姓名', width: 110 }, + { colKey: 'email', title: '邮箱', minWidth: 160, ellipsis: true }, + { colKey: 'home', title: '当前归属空间(登录落点)', width: 180 }, + { colKey: 'in_roster', title: '名册', width: 80 }, +] + +const openAdopt = async () => { + adoptVisible.value = true + adoptLoaded.value = false + adoptList.value = [] + try { + const res = await listAdoptableUsers() + adoptList.value = unwrap(res) || [] + adoptLoaded.value = true + } catch (err: any) { + MessagePlugin.error(err?.response?.data?.message || '加载可收编成员失败') + } +} + +const onAdopt = async () => { + if (!adoptList.value.length) return + adopting.value = true + try { + const res = await adoptHomeTenant(adoptList.value.map((u) => u.id)) + const result = unwrap(res) + const skipped = result?.skipped || [] + MessagePlugin.success(`已收编 ${result?.adopted ?? 0} 名成员,自下次登录起默认进入本空间`) + // 预览与收编之间成员关系可能变化(被移出/停用),逐条原因只提示首条避免刷屏。 + if (skipped.length) { + const first = skipped[0] + MessagePlugin.warning( + `${skipped.length} 名成员被跳过:如 ${first.username} ${first.reason}${skipped.length > 1 ? ' 等' : ''}`, + ) + } + adoptVisible.value = false + loadEmployees() + } catch (err: any) { + MessagePlugin.error(err?.response?.data?.message || '收编失败') + } finally { + adopting.value = false + } +} + const openRoles = (row: OrgEmployee) => { activeEmployee.value = row roleSelection.value = (row.roles || []).filter((r) => r !== 'trainee') @@ -808,4 +907,8 @@ onMounted(() => { gap: 8px; justify-content: flex-end; } +// 收编弹窗说明文案 +.adopt-hint { + margin: 0 0 10px; +} diff --git a/internal/application/repository/orgcenter.go b/internal/application/repository/orgcenter.go index a9b6a89..9d4db5f 100644 --- a/internal/application/repository/orgcenter.go +++ b/internal/application/repository/orgcenter.go @@ -248,6 +248,31 @@ func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint return users, err } +// ListAdoptableUsers lists the tenant's active members whose home tenant +// (users.tenant_id) is not this workspace — the preview source for +// 「收编到本空间」. 归属列为 NULL(无归属账号)的成员同样是候选:Postgres 的 +// `NULL != x` 不命中,须 COALESCE 兜底(仓库测试跑在 SQLite 上,两者兼容)。 +// 名册 join 与 ListTenantUsers 同口径;home 租户名联查 tenants(带软删过滤) +// 供 UI 确认来源空间。 +func (r *orgCenterRepository) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) { + var users []*types.OrgAdoptableUser + err := r.db.WithContext(ctx). + Table("users u"). + Select(`u.id, u.username, u.email, u.display_name, + COALESCE(u.tenant_id, 0) AS home_tenant_id, + COALESCE(ht.name, '') AS home_tenant_name, + (m.id IS NOT NULL) AS in_roster`). + Joins("JOIN tenant_members tm ON tm.user_id = u.id AND tm.tenant_id = ? "+ + "AND tm.status = 'active' AND tm.deleted_at IS NULL", tenantID). + Joins("LEFT JOIN org_employees m ON m.user_id = u.id AND m.tenant_id = ? AND m.deleted_at IS NULL", tenantID). + Joins("LEFT JOIN tenants ht ON ht.id = u.tenant_id AND ht.deleted_at IS NULL"). + Where("u.is_active = TRUE AND u.deleted_at IS NULL"). + Where("COALESCE(u.tenant_id, 0) != ?", tenantID). + Order("u.created_at ASC"). + Scan(&users).Error + return users, err +} + // GetUsernamesByUserIDs resolves platform accounts (users.username) for the // given user IDs within the tenant — used to backfill employee_no on import // (工号 = 平台账号,员工编号型 IdP 同步而来;见 ListTenantUsers 的成员口径注释)。 diff --git a/internal/application/repository/orgcenter_adoptable_users_test.go b/internal/application/repository/orgcenter_adoptable_users_test.go new file mode 100644 index 0000000..f5948e9 --- /dev/null +++ b/internal/application/repository/orgcenter_adoptable_users_test.go @@ -0,0 +1,104 @@ +package repository + +import ( + "context" + "testing" + "time" + + "academy/internal/types" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// 收编预览数据源回归:ListAdoptableUsers 须列出「归属空间不在本空间」的活跃 +// 成员,含两类边界——归属列为 NULL 的无归属账号(Postgres 的 `NULL != x` 不 +// 命中,COALESCE 兜底)与归属本空间者不列。名册标记与 home 租户名供 UI 确认。 +func TestListAdoptableUsers(t *testing.T) { + db, err := gorm.Open(sqlite.Open("file:org-adoptable?mode=memory&cache=shared"), &gorm.Config{}) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + if err := db.AutoMigrate(&types.User{}, &types.Tenant{}, &types.TenantMember{}, &types.OrgEmployee{}); err != nil { + t.Fatalf("migrate schema: %v", err) + } + + base := time.Date(2026, 11, 24, 3, 0, 0, 0, time.UTC) + mkUser := func(id string, home uint64, offset time.Duration) *types.User { + return &types.User{ + ID: id, Username: id, Email: id + "@casdoor.local", + TenantID: home, IsActive: true, + CreatedAt: base.Add(offset), UpdatedAt: base.Add(offset), + } + } + // personal-home:归属个人空间 3,典型收编对象;tenantless:归属 NULL; + // local:归属本空间 2(不列);inactive:停用账号不列。 + for _, u := range []*types.User{ + mkUser("personal-home", 3, 0), + mkUser("tenantless", 0, time.Hour), + mkUser("local", 2, 2*time.Hour), + mkUser("inactive", 4, 3*time.Hour), + } { + if err := db.Create(u).Error; err != nil { + t.Fatalf("insert user %s: %v", u.ID, err) + } + } + // 停用账号以软删模拟(与 GetUsersByIDs/ListTenantUsers 的可见口径一致)。 + if err := db.Delete(&types.User{}, "id = ?", "inactive").Error; err != nil { + t.Fatalf("soft-delete user: %v", err) + } + for _, m := range []*types.TenantMember{ + {UserID: "personal-home", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base}, + {UserID: "tenantless", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(time.Hour)}, + {UserID: "local", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(2 * time.Hour)}, + {UserID: "inactive", TenantID: 2, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: base.Add(3 * time.Hour)}, + } { + if err := db.Create(m).Error; err != nil { + t.Fatalf("insert membership %s: %v", m.UserID, err) + } + } + if err := db.Create(&types.Tenant{ID: 3, Name: "26080007's Workspace", Status: "active"}).Error; err != nil { + t.Fatalf("insert home tenant: %v", err) + } + if err := db.Create(&types.OrgEmployee{ + TenantID: 2, UserID: "personal-home", EmployeeNo: "26080007", Status: "active", + }).Error; err != nil { + t.Fatalf("insert roster entry: %v", err) + } + + repo := &orgCenterRepository{db: db} + users, err := repo.ListAdoptableUsers(context.Background(), 2) + if err != nil { + t.Fatalf("ListAdoptableUsers: %v", err) + } + + byID := map[string]*types.OrgAdoptableUser{} + for _, u := range users { + byID[u.ID] = u + } + if len(users) != 2 { + t.Fatalf("want exactly personal-home + tenantless, got %+v", users) + } + if u := byID["personal-home"]; u == nil { + t.Fatal("personal-home missing from adoptable list") + } else { + if u.HomeTenantID != 3 || u.HomeTenantName != "26080007's Workspace" { + t.Fatalf("personal-home home = %d/%q, want 3/26080007's Workspace", u.HomeTenantID, u.HomeTenantName) + } + if !u.InRoster { + t.Fatal("personal-home InRoster = false, want true") + } + if u.Username != "personal-home" || u.Email != "personal-home@casdoor.local" { + t.Fatalf("personal-home display fields wrong: %+v", u) + } + } + if u := byID["tenantless"]; u == nil { + t.Fatal("tenantless (NULL home) missing from adoptable list — COALESCE guard failed") + } else if u.HomeTenantID != 0 || u.HomeTenantName != "" { + t.Fatalf("tenantless home should be 0/'', got %d/%q", u.HomeTenantID, u.HomeTenantName) + } + for _, absent := range []string{"local", "inactive"} { + if byID[absent] != nil { + t.Fatalf("user %s must not appear in adoptable list", absent) + } + } +} diff --git a/internal/application/service/orgcenter.go b/internal/application/service/orgcenter.go index 71a3121..edb79e8 100644 --- a/internal/application/service/orgcenter.go +++ b/internal/application/service/orgcenter.go @@ -2,8 +2,10 @@ package service import ( "context" + "encoding/json" "fmt" "strings" + "time" "academy/internal/errors" "academy/internal/logger" @@ -11,16 +13,29 @@ import ( "academy/internal/types/interfaces" "github.com/google/uuid" ) + // orgCenterService 组织中心业务服务:部门维护、员工档案管理、模块角色绑定。 // 组织数据归租户所有;业务模块(企业培训等)按 module_key 绑定各自角色, // 部门/岗位/姓名只维护一份。 type orgCenterService struct { repo interfaces.OrgCenterRepository + // 收编归属空间(登录默认落点)所需依赖。依赖仓库(UserRepository/ + // TenantMemberRepository)而非服务:tenantMemberService 已反向依赖本服务, + // userService 又依赖 memberService,引用服务层会成 DI 环。audit 可空 + // (nil ⇒ 不写审计,业务照常);users/members 为 nil 时收编接口不可用。 + users interfaces.UserRepository + members interfaces.TenantMemberRepository + audit interfaces.AuditLogService } // NewOrgCenterService constructs the org center service. -func NewOrgCenterService(repo interfaces.OrgCenterRepository) interfaces.OrgCenterService { - return &orgCenterService{repo: repo} +func NewOrgCenterService( + repo interfaces.OrgCenterRepository, + users interfaces.UserRepository, + members interfaces.TenantMemberRepository, + audit interfaces.AuditLogService, +) interfaces.OrgCenterService { + return &orgCenterService{repo: repo, users: users, members: members, audit: audit} } // --------------------------------------------------------------------------- @@ -260,6 +275,135 @@ func (s *orgCenterService) ListTenantUsers(ctx context.Context, tenantID uint64) return s.repo.ListTenantUsers(ctx, tenantID) } +// --------------------------------------------------------------------------- +// 收编归属空间(登录默认落点) +// --------------------------------------------------------------------------- + +// ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。 +func (s *orgCenterService) ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) { + return s.repo.ListAdoptableUsers(ctx, tenantID) +} + +// AdoptHomeTenant 把指定成员的归属空间(users.tenant_id,登录/refresh 默认落点) +// 批量收编为本空间。场景:员工首登自动开通个人空间(auth.default_tenant_mode +// =create_personal 默认),归属指针停在个人空间,登录后看到的组织架构/培训 +// 数据是个人空间里那份空数据;管理员在本空间维护好组织架构后,用收编把成员 +// 的默认落点改回本空间。语义: +// - 只动归属指针与「最近活跃租户」偏好,成员关系/角色/个人空间数据都不变, +// 成员仍可经空间切换器自行改回,非破坏性; +// - 仅收编本空间活跃成员(逐条校验,缺失跳过并回传原因,不整批失败); +// - 跨空间账号(CanAccessAllTenants)不自动收编——其落点是刻意配置; +// - 同步「最近活跃租户」偏好指向本空间:登录路径(resolveLoginTenantID) +// 优先读偏好,只改归属不改偏好时,切过空间的成员下次登录仍落回旧空间; +// - 收编成功的成员补跑一次自动入册(仅补空、幂等),把同步部门带进名册; +// - 已有会话不受影响,自下次登录/refresh 起落到本空间。 +func (s *orgCenterService) AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error) { + if tenantID == 0 { + return nil, errors.NewBadRequestError("缺少目标空间") + } + if len(userIDs) == 0 { + return nil, errors.NewBadRequestError("请选择要收编的成员") + } + if s.users == nil || s.members == nil { + return nil, errors.NewInternalServerError("收编功能不可用:依赖服务未装配") + } + result := &types.OrgAdoptResult{Skipped: []*types.OrgAdoptSkip{}} + adopted := make([]string, 0, len(userIDs)) + for _, userID := range userIDs { + if s.adoptOneHomeTenant(ctx, tenantID, userID, result) == nil { + adopted = append(adopted, userID) + } + } + result.Adopted = len(adopted) + // 收编成功者补跑自动入册(fail-open,与成员加入路径同约定):名册缺行时 + // 按平台账号补建,dept_code/dept_name 命中已维护部门时自动匹配。失败只 + // 告警:归属指针已落库,名册可由成员加入路径或手动导入补齐。 + if len(adopted) > 0 { + if err := s.EnsureEmployeesForUsers(ctx, tenantID, adopted); err != nil { + logger.Warnf(ctx, "[OrgCenter] adopt home tenant: auto-roster backfill failed (adoption kept): tenant=%d err=%v", + tenantID, err) + } + } + s.emitAdoptAudit(ctx, tenantID, len(adopted), result.Skipped) + logger.Infof(ctx, "[OrgCenter] home tenants adopted, tenant=%d adopted=%d skipped=%d", + tenantID, len(adopted), len(result.Skipped)) + return result, nil +} + +// adoptOneHomeTenant 收编单个成员;返回 nil 表示收编成功,否则为跳过记录 +// (已追加进 result.Skipped,原因逐条回传 UI)。 +func (s *orgCenterService) adoptOneHomeTenant(ctx context.Context, tenantID uint64, userID string, result *types.OrgAdoptResult) *types.OrgAdoptSkip { + skipWith := func(u *types.User, reason string) *types.OrgAdoptSkip { + entry := &types.OrgAdoptSkip{UserID: userID, Reason: reason} + if u != nil { + entry.Username = u.Username + entry.DisplayName = u.DisplayName + } + result.Skipped = append(result.Skipped, entry) + return entry + } + user, err := s.users.GetUserByID(ctx, userID) + if err != nil || user == nil { + // GetUserByID 带软删过滤:已删除账号在此按不存在处理。 + return skipWith(nil, "平台账号不存在") + } + if !user.IsActive { + return skipWith(user, "账号已停用") + } + if user.CanAccessAllTenants { + return skipWith(user, "跨空间账号不自动收编") + } + if user.TenantID == tenantID { + return skipWith(user, "归属空间已是本空间") + } + member, err := s.members.Get(ctx, userID, tenantID) + if err != nil { + return skipWith(user, "查询成员关系失败") + } + if member == nil || member.Status != types.TenantMemberStatusActive { + return skipWith(user, "非本空间成员,请先邀请或批量导入加入") + } + // 归属指针 + 最近活跃租户偏好一起指向本空间(见 AdoptHomeTenant 语义注释)。 + user.TenantID = tenantID + user.Preferences.LastActiveTenantID = &tenantID + user.UpdatedAt = time.Now() + if err := s.users.UpdateUser(ctx, user); err != nil { + return skipWith(user, "写入归属空间失败:"+err.Error()) + } + return nil +} + +// emitAdoptAudit 写一条批量收编审计(best-effort:audit 不可用不阻断, +// 与 tenantMemberService.emitAudit 同约定)。单批一条,Details 记名单与 +// 统计,供审计侧对账。 +func (s *orgCenterService) emitAdoptAudit(ctx context.Context, tenantID uint64, adopted int, skipped []*types.OrgAdoptSkip) { + if s.audit == nil { + return + } + ids := make([]string, 0, len(skipped)) + for _, sk := range skipped { + ids = append(ids, sk.UserID) + } + details, err := json.Marshal(map[string]any{ + "user_ids": ids, + "adopted": adopted, + "skipped": len(skipped), + }) + if err != nil { + return + } + actor, _ := types.UserIDFromContext(ctx) + _ = s.audit.Log(ctx, &types.AuditLog{ + TenantID: tenantID, + ActorUserID: actor, + ActorRole: string(types.TenantRoleFromContext(ctx)), + Action: types.AuditActionMemberHomeAdopted, + TargetType: "tenant_member", + Outcome: types.AuditOutcomeSuccess, + Details: details, + }) +} + // --------------------------------------------------------------------------- // 模块角色绑定 // --------------------------------------------------------------------------- diff --git a/internal/application/service/orgcenter_adopt_test.go b/internal/application/service/orgcenter_adopt_test.go new file mode 100644 index 0000000..141bc1e --- /dev/null +++ b/internal/application/service/orgcenter_adopt_test.go @@ -0,0 +1,185 @@ +package service + +import ( + "context" + "testing" + + "academy/internal/types" + "academy/internal/types/interfaces" +) + +// 收编归属空间(AdoptHomeTenant):把成员的登录默认落点(users.tenant_id + +// 最近活跃租户偏好)批量改指本空间。场景回归:员工首登开了个人空间后,登录 +// 落在个人空间,看不到本空间维护的组织架构;收编只动归属指针,成员关系与 +// 个人空间数据不变。 + +// fakeAdoptOrgRepo 组织中心仓库桩:入册补建(EnsureEmployeesForUsers)路径。 +type fakeAdoptOrgRepo struct { + interfaces.OrgCenterRepository + roster []*types.OrgEmployee // InsertEmployeesIfAbsent 收到的补建行 + userInfos []*types.TrainingUserInfo +} + +func (f *fakeAdoptOrgRepo) ListDepts(context.Context, uint64) ([]*types.OrgDept, error) { + return []*types.OrgDept{{ID: "d1", Name: "生产一部", Code: "D01"}}, nil +} + +func (f *fakeAdoptOrgRepo) GetRosterUserInfos(_ context.Context, _ uint64, userIDs []string) ([]*types.TrainingUserInfo, error) { + byID := map[string]*types.TrainingUserInfo{} + for _, u := range f.userInfos { + byID[u.ID] = u + } + out := make([]*types.TrainingUserInfo, 0, len(userIDs)) + for _, id := range userIDs { + if u, ok := byID[id]; ok { + out = append(out, u) + } + } + return out, nil +} + +func (f *fakeAdoptOrgRepo) InsertEmployeesIfAbsent(_ context.Context, employees []*types.OrgEmployee) error { + f.roster = append(f.roster, employees...) + return nil +} + +// fakeAdoptUserRepo 用户仓库桩:收编读改写 users.tenant_id / 偏好。 +type fakeAdoptUserRepo struct { + interfaces.UserRepository + users map[string]*types.User + updated []*types.User +} + +func (f *fakeAdoptUserRepo) GetUserByID(_ context.Context, id string) (*types.User, error) { + if u, ok := f.users[id]; ok { + return u, nil + } + return nil, nil +} + +func (f *fakeAdoptUserRepo) UpdateUser(_ context.Context, u *types.User) error { + f.updated = append(f.updated, u) + return nil +} + +// fakeAdoptMemberRepo 成员仓库桩:收编前校验目标空间活跃成员关系。 +type fakeAdoptMemberRepo struct { + interfaces.TenantMemberRepository + members map[string]*types.TenantMember // key: user_id(目标空间) +} + +func (f *fakeAdoptMemberRepo) Get(_ context.Context, userID string, _ uint64) (*types.TenantMember, error) { + if m, ok := f.members[userID]; ok { + return m, nil + } + return nil, nil +} + +func newAdoptService(org *fakeAdoptOrgRepo, users *fakeAdoptUserRepo, members *fakeAdoptMemberRepo) interfaces.OrgCenterService { + return NewOrgCenterService(org, users, members, nil) +} + +func TestAdoptHomeTenantMovesHomeAndPreference(t *testing.T) { + org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{ + {ID: "u-sun", Username: "26080007", DeptCode: "D01", DeptName: "生产一部"}, + }} + pref := uint64(9) // 旧偏好指向个人空间:收编必须一并改指,否则登录仍落旧空间 + users := &fakeAdoptUserRepo{users: map[string]*types.User{ + "u-sun": {ID: "u-sun", Username: "26080007", IsActive: true, TenantID: 9, + Preferences: types.UserPreferences{LastActiveTenantID: &pref}}, + }} + members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{ + "u-sun": {UserID: "u-sun", TenantID: 2, Status: types.TenantMemberStatusActive}, + }} + svc := newAdoptService(org, users, members) + + result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{"u-sun"}) + if err != nil { + t.Fatalf("AdoptHomeTenant: %v", err) + } + if result.Adopted != 1 || len(result.Skipped) != 0 { + t.Fatalf("unexpected result: adopted=%d skipped=%+v", result.Adopted, result.Skipped) + } + saved := users.updated[0] + if saved.TenantID != 2 { + t.Fatalf("home tenant not moved: %d", saved.TenantID) + } + if saved.Preferences.LastActiveTenantID == nil || *saved.Preferences.LastActiveTenantID != 2 { + t.Fatalf("LastActiveTenantID not pointed at target: %+v", saved.Preferences.LastActiveTenantID) + } + // 收编成功者补跑自动入册:名册补建且部门按 dept_code 匹配。 + if len(org.roster) != 1 || org.roster[0].UserID != "u-sun" || org.roster[0].DeptID != "d1" { + t.Fatalf("roster backfill missing or dept unmatched: %+v", org.roster) + } +} + +func TestAdoptHomeTenantSkipsNonMembersAndSuperusers(t *testing.T) { + org := &fakeAdoptOrgRepo{userInfos: []*types.TrainingUserInfo{ + {ID: "u-in", Username: "26080007"}, + }} + users := &fakeAdoptUserRepo{users: map[string]*types.User{ + "u-in": {ID: "u-in", Username: "26080007", IsActive: true, TenantID: 9}, + "u-super": {ID: "u-super", Username: "admin", IsActive: true, CanAccessAllTenants: true}, + "u-out": {ID: "u-out", Username: "26010001", IsActive: true, TenantID: 9}, + "u-off": {ID: "u-off", Username: "26010002", IsActive: false, TenantID: 9}, + "u-home": {ID: "u-home", Username: "26010003", IsActive: true, TenantID: 2}, + // u-ghost 不在用户表(账号已消失),收编按「平台账号不存在」跳过。 + }} + members := &fakeAdoptMemberRepo{members: map[string]*types.TenantMember{ + // u-in 是本空间活跃成员(唯一收编对象);u-super 是成员但跨空间账号 + // 不自动收编;u-off 成员关系已停用。 + "u-in": {UserID: "u-in", TenantID: 2, Status: types.TenantMemberStatusActive}, + "u-super": {UserID: "u-super", TenantID: 2, Status: types.TenantMemberStatusActive}, + "u-off": {UserID: "u-off", TenantID: 2, Status: types.TenantMemberStatusSuspended}, + }} + svc := newAdoptService(org, users, members) + + result, err := svc.AdoptHomeTenant(context.Background(), 2, []string{ + "u-in", "u-super", "u-out", "u-off", "u-home", "u-ghost", + }) + if err != nil { + t.Fatalf("AdoptHomeTenant: %v", err) + } + if result.Adopted != 1 { + t.Fatalf("only u-in should be adopted, got %d (%+v)", result.Adopted, result.Skipped) + } + reasons := map[string]string{} + for _, sk := range result.Skipped { + reasons[sk.UserID] = sk.Reason + } + want := map[string]string{ + "u-super": "跨空间账号不自动收编", + "u-out": "非本空间成员,请先邀请或批量导入加入", + // 停用账号在成员关系校验前拦截:账号不可用,收编无意义。 + "u-off": "账号已停用", + "u-home": "归属空间已是本空间", + "u-ghost": "平台账号不存在", + } + for id, reason := range want { + if reasons[id] != reason { + t.Fatalf("user %s reason = %q, want %q", id, reasons[id], reason) + } + } + // 仅收编成功者(u-in)触发补建;跳过者不写任何用户行。 + if len(org.roster) != 1 || org.roster[0].UserID != "u-in" { + t.Fatalf("roster backfill should only cover adopted users: %+v", org.roster) + } + if len(users.updated) != 1 || users.updated[0].ID != "u-in" { + t.Fatalf("only adopted user should be persisted: %+v", users.updated) + } +} + +func TestAdoptHomeTenantGuards(t *testing.T) { + svc := newAdoptService(&fakeAdoptOrgRepo{}, &fakeAdoptUserRepo{}, &fakeAdoptMemberRepo{}) + if _, err := svc.AdoptHomeTenant(context.Background(), 0, []string{"u"}); err == nil { + t.Fatal("zero tenant must be rejected") + } + if _, err := svc.AdoptHomeTenant(context.Background(), 2, nil); err == nil { + t.Fatal("empty user list must be rejected") + } + // 依赖未装配(users/members 为 nil)时报错而不是 panic。 + noDep := NewOrgCenterService(&fakeAdoptOrgRepo{}, nil, nil, nil) + if _, err := noDep.AdoptHomeTenant(context.Background(), 2, []string{"u"}); err == nil { + t.Fatal("missing deps must error, not panic") + } +} diff --git a/internal/application/service/orgcenter_import_backfill_test.go b/internal/application/service/orgcenter_import_backfill_test.go index afcf756..90ca102 100644 --- a/internal/application/service/orgcenter_import_backfill_test.go +++ b/internal/application/service/orgcenter_import_backfill_test.go @@ -52,7 +52,7 @@ func newFakeOrgRepo() *fakeOrgRepo { func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) { repo := newFakeOrgRepo() - svc := NewOrgCenterService(repo) + svc := NewOrgCenterService(repo, nil, nil, nil) employees := []*types.OrgEmployee{ {UserID: "u-qu", DeptID: "d1"}, // 留空 → 回填平台账号 {UserID: "u-jin", DeptID: "d1"}, // 留空 → 回填平台账号 @@ -76,7 +76,7 @@ func TestImportEmployeesBackfillsEmployeeNoFromUsername(t *testing.T) { func TestImportEmployeesRejectsDuplicateEmployeeNo(t *testing.T) { repo := newFakeOrgRepo() - svc := NewOrgCenterService(repo) + svc := NewOrgCenterService(repo, nil, nil, nil) // u-qu 回填出 26010003,与 u-jin 的显式 26010003 撞号 → 整批拒绝。 employees := []*types.OrgEmployee{ {UserID: "u-qu", DeptID: "d1"}, diff --git a/internal/application/service/tenant_member_sync_test.go b/internal/application/service/tenant_member_sync_test.go index ee3a0ad..d54aead 100644 --- a/internal/application/service/tenant_member_sync_test.go +++ b/internal/application/service/tenant_member_sync_test.go @@ -215,7 +215,7 @@ func newSyncService( AdminOrganization: "built-in", EmailFallbackDomain: "casdoor.local", }} - orgSvc := NewOrgCenterService(orgRepo) + orgSvc := NewOrgCenterService(orgRepo, nil, nil, nil) return NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, orgSvc) } @@ -401,7 +401,7 @@ func TestSyncCasdoorGrantNotSupported(t *testing.T) { AdminOrganization: "built-in", }} // ClientID 为空 → client.Enabled() 为 false → 配置提示路径。 - svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) + svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil)) _, err := svc.SyncMembers(context.Background(), 7, "op-1") if err == nil || !strings.Contains(err.Error(), "未启用") { t.Fatalf("disabled config should surface actionable error, got: %v", err) @@ -431,7 +431,7 @@ func TestSyncCasdoorPasswordMode(t *testing.T) { AdminPassword: "secret-pwd", EmailFallbackDomain: "casdoor.local", }} - svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) + svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil)) res, err := svc.SyncMembers(context.Background(), 7, "op-1") if err != nil { @@ -465,7 +465,7 @@ func TestSyncCasdoorWrappedPayload(t *testing.T) { AdminPassword: "secret-pwd", EmailFallbackDomain: "casdoor.local", }} - svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo)) + svc := NewCasdoorMemberSyncService(cfg, userSvc, memberSvc, NewOrgCenterService(orgRepo, nil, nil, nil)) res, err := svc.SyncMembers(context.Background(), 7, "op-1") if err != nil { t.Fatalf("SyncMembers(wrapped): %v", err) diff --git a/internal/handler/orgcenter/orgcenter.go b/internal/handler/orgcenter/orgcenter.go index 63667e6..e79e6c1 100644 --- a/internal/handler/orgcenter/orgcenter.go +++ b/internal/handler/orgcenter/orgcenter.go @@ -2,6 +2,7 @@ package orgcenter import ( "encoding/json" + "fmt" "net/http" "strconv" @@ -199,6 +200,69 @@ func (h *Handler) ListPlatformUsers(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": true, "data": users}) } +// --------------------------------------------------------------------------- +// 归属空间收编(登录默认落点;路由层 Owner 限定,与成员批量导入同权限级别) +// --------------------------------------------------------------------------- + +// orgAdoptMaxUsers 单次收编人数上限(与成员批量导入行数上限同量级,防超大批次)。 +const orgAdoptMaxUsers = 2000 + +// ListAdoptableUsers GET /org/employees/adoptable — 收编预览:归属空间不在 +// 本空间的活跃成员(员工首登开了个人空间时,登录会落进个人空间看不到本空间 +// 维护的组织架构,管理员用收编把默认落点改回本空间)。 +func (h *Handler) ListAdoptableUsers(c *gin.Context) { + users, err := h.svc.ListAdoptableUsers(c.Request.Context(), callerTenantID(c)) + if err != nil { + _ = c.Error(err) + return + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": users}) +} + +// adoptHomeTenantRequest is the body of POST /org/employees/adopt-home. +type adoptHomeTenantRequest struct { + UserIDs []string `json:"user_ids" binding:"required,min=1"` +} + +// AdoptHomeTenant POST /org/employees/adopt-home — 批量收编归属空间到本空间。 +// 只改成员的登录默认落点(users.tenant_id + 最近活跃租户偏好),不动成员关系 +// 与个人空间数据;逐条跳过非本空间成员等情形并回传原因。 +func (h *Handler) AdoptHomeTenant(c *gin.Context) { + ctx := c.Request.Context() + var req adoptHomeTenantRequest + if err := c.ShouldBindJSON(&req); err != nil { + _ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error())) + return + } + if len(req.UserIDs) > orgAdoptMaxUsers { + _ = c.Error(errors.NewBadRequestError(fmt.Sprintf("单次最多收编 %d 名成员", orgAdoptMaxUsers))) + return + } + // 去重保序:重复/空 id 只收编一次,统计口径不重复计数。 + seen := make(map[string]struct{}, len(req.UserIDs)) + userIDs := make([]string, 0, len(req.UserIDs)) + for _, id := range req.UserIDs { + if id == "" { + continue + } + if _, dup := seen[id]; dup { + continue + } + seen[id] = struct{}{} + userIDs = append(userIDs, id) + } + if len(userIDs) == 0 { + _ = c.Error(errors.NewBadRequestError("请选择要收编的成员")) + return + } + result, err := h.svc.AdoptHomeTenant(ctx, callerTenantID(c), userIDs) + if err != nil { + _ = c.Error(err) + return + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": result}) +} + // --------------------------------------------------------------------------- // 模块角色绑定 // --------------------------------------------------------------------------- @@ -216,8 +280,8 @@ func (h *Handler) ListModuleMembers(c *gin.Context) { // putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id. type putModuleMemberRequest struct { - Roles []string `json:"roles"` - Extra map[string]any `json:"extra"` + Roles []string `json:"roles"` + Extra map[string]any `json:"extra"` } // PutModuleMember PUT /org/modules/:module_key/members/:employee_id diff --git a/internal/router/routes_org.go b/internal/router/routes_org.go index a47d312..92e5423 100644 --- a/internal/router/routes_org.go +++ b/internal/router/routes_org.go @@ -34,6 +34,12 @@ func RegisterOrgRoutes(r *gin.RouterGroup, h *orgcenter.Handler, th *training.Ha orgGroup.GET("/platform-users", g.Contributor(), h.ListPlatformUsers) orgGroup.POST("/employees/import", g.Contributor(), h.ImportEmployees) + // ---- 归属空间收编(登录默认落点) ---- + // Owner 限定:改的是账号级登录落点(users.tenant_id + 最近活跃租户偏好), + // 与成员批量导入/ Casdoor 同步同权限级别,组织架构页仅 Owner 可见入口。 + orgGroup.GET("/employees/adoptable", g.Owner(), h.ListAdoptableUsers) + orgGroup.POST("/employees/adopt-home", g.Owner(), h.AdoptHomeTenant) + // ---- 职称角色 / 企微账号(培训域语义,handler 内 requireRoles(HR,经理) 细控) ---- // 职称角色页(培训 members 子页)迁入组织架构页后的 /org 域别名路由: // 复用培训 handler,角色绑定仍写 module_key='training' 的 org_module_members。 diff --git a/internal/types/audit_log.go b/internal/types/audit_log.go index a5ce102..cc483a2 100644 --- a/internal/types/audit_log.go +++ b/internal/types/audit_log.go @@ -50,6 +50,13 @@ const ( // AuditActionInvitationExpired fires when the lazy sweep transitions // an overdue pending row to expired. Actor is empty (system). AuditActionInvitationExpired AuditAction = "rbac.invitation_expired" + // AuditActionMemberHomeAdopted fires when a tenant Owner batch-adopts + // members' home tenants (users.tenant_id + LastActiveTenantID) into the + // operating workspace (组织架构「收编到本空间」). The membership rows are + // untouched — only the default-landing pointer moves — so this is + // distinct from member_added. Details payload carries + // {user_ids, adopted, skipped} for batch reconciliation. + AuditActionMemberHomeAdopted AuditAction = "rbac.member_home_adopted" // VectorStore lifecycle actions. Emitted by VectorStoreService. // Cover both env-store-derived (__env_*) and DB store create / diff --git a/internal/types/interfaces/orgcenter.go b/internal/types/interfaces/orgcenter.go index ce894a4..723ad98 100644 --- a/internal/types/interfaces/orgcenter.go +++ b/internal/types/interfaces/orgcenter.go @@ -31,6 +31,8 @@ type OrgCenterRepository interface { // ListTenantUsers 平台用户列表(含是否已在组织名册),员工导入选择器数据源。 ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) + // ListAdoptableUsers 归属空间不在本空间的活跃成员(收编预览数据源)。 + ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) // GetUsernamesByUserIDs 租户内指定用户的平台账号映射(员工导入空工号回填用)。 GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error) // GetRosterUserInfos 指定成员的入册所需字段(平台账号 + 同步部门)。 @@ -66,6 +68,12 @@ type OrgCenterService interface { // ListTenantUsers 平台用户列表(员工导入选择器数据源)。 ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) + // ListAdoptableUsers 归属空间不在本空间的活跃成员列表(收编预览)。 + ListAdoptableUsers(ctx context.Context, tenantID uint64) ([]*types.OrgAdoptableUser, error) + // AdoptHomeTenant 批量收编:把指定成员的归属空间(登录默认落点)改为本空间。 + // 仅收编本空间活跃成员,逐条跳过并回传原因;成功后补跑一次自动入册。 + AdoptHomeTenant(ctx context.Context, tenantID uint64, userIDs []string) (*types.OrgAdoptResult, error) + // 模块角色绑定 GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error) PutModuleMember(ctx context.Context, tenantID uint64, member *types.OrgModuleMember) (*types.OrgModuleMember, error) diff --git a/internal/types/orgcenter.go b/internal/types/orgcenter.go index 003f745..d367fd2 100644 --- a/internal/types/orgcenter.go +++ b/internal/types/orgcenter.go @@ -23,14 +23,14 @@ const ( // OrgDept 部门树节点(原 TrainingDept,表随 000137 迁移更名)。 type OrgDept struct { - ID string `json:"id" gorm:"type:varchar(36);primaryKey"` - TenantID uint64 `json:"tenant_id" gorm:"not null;index"` - ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"` - Name string `json:"name" gorm:"type:varchar(128);not null"` - Code string `json:"code" gorm:"type:varchar(64);default:''"` - Sort int `json:"sort" gorm:"default:0"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + TenantID uint64 `json:"tenant_id" gorm:"not null;index"` + ParentID string `json:"parent_id" gorm:"type:varchar(36);default:''"` + Name string `json:"name" gorm:"type:varchar(128);not null"` + Code string `json:"code" gorm:"type:varchar(64);default:''"` + Sort int `json:"sort" gorm:"default:0"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"-" gorm:"index"` } @@ -39,17 +39,17 @@ func (OrgDept) TableName() string { return "org_depts" } // OrgEmployee 租户员工档案(1:1 users;原 TrainingMember,roles 列已迁入模块绑定表)。 type OrgEmployee struct { - ID string `json:"id" gorm:"type:varchar(36);primaryKey"` - TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"` - UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"` - EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"` - DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"` - Post string `json:"post" gorm:"type:varchar(128);default:''"` - LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"` - WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"` - Status string `json:"status" gorm:"type:varchar(16);default:'active'"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_tr_members_tenant_user"` + UserID string `json:"user_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_tr_members_tenant_user"` + EmployeeNo string `json:"employee_no" gorm:"type:varchar(64);default:''"` + DeptID string `json:"dept_id" gorm:"type:varchar(36);default:'';index"` + Post string `json:"post" gorm:"type:varchar(128);default:''"` + LecturerRate float64 `json:"lecturer_rate" gorm:"default:0"` + WecomUserid string `json:"wecom_userid" gorm:"type:varchar(64);default:''"` + Status string `json:"status" gorm:"type:varchar(16);default:'active'"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"-" gorm:"index"` // 联查只读展示字段(不落库): @@ -76,14 +76,14 @@ func (m *OrgEmployee) OrgRoleList() []string { // OrgModuleMember 业务模块在员工档案上的角色绑定(职称角色/审图员/检核员...按 module_key 区分)。 type OrgModuleMember struct { - ID string `json:"id" gorm:"type:varchar(36);primaryKey"` - TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"` - ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"` - EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"` - Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"` - Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id" gorm:"type:varchar(36);primaryKey"` + TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:uq_org_module_members"` + ModuleKey string `json:"module_key" gorm:"type:varchar(50);not null;uniqueIndex:uq_org_module_members"` + EmployeeID string `json:"employee_id" gorm:"type:varchar(36);not null;uniqueIndex:uq_org_module_members"` + Roles JSON `json:"roles" gorm:"type:jsonb;default:'[]'"` + Extra JSON `json:"extra" gorm:"type:jsonb;default:'{}'"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"-" gorm:"index"` } @@ -97,3 +97,31 @@ type OrgListQuery struct { Page int PageSize int } + +// OrgAdoptableUser 可收编成员(归属空间不在本空间的活跃成员),「收编到本空间」 +// 预览行。归属空间(users.tenant_id)决定登录/refresh 默认进入的工作区;员工 +// 首登自动开通个人空间(create_personal 默认)后归属指针停在个人空间,收编把 +// 该指针改指本空间——成员关系、角色与个人空间数据均不变,非破坏性。 +type OrgAdoptableUser struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + Email string `json:"email"` + HomeTenantID uint64 `json:"home_tenant_id"` + HomeTenantName string `json:"home_tenant_name"` + InRoster bool `json:"in_roster"` +} + +// OrgAdoptSkip 批量收编中单条跳过记录(逐条原因回传 UI 展示)。 +type OrgAdoptSkip struct { + UserID string `json:"user_id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + Reason string `json:"reason"` +} + +// OrgAdoptResult 批量收编结果统计。 +type OrgAdoptResult struct { + Adopted int `json:"adopted"` + Skipped []*OrgAdoptSkip `json:"skipped"` +}