deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
员工首登自动开通个人空间(create_personal 默认)后,归属空间(users.tenant_id)
与「最近活跃租户」偏好停在个人空间,登录后看到的是个人空间里那份空的组织
架构/培训数据,模板下载也没有部门下拉。空间 Owner 现可一键收编:
1. GET /org/employees/adoptable 收编预览:归属空间不在本空间的活跃成员
(COALESCE 兜底 NULL 归属,联查名册标记与归属空间名供确认);
2. POST /org/employees/adopt-home 批量收编:逐条校验不整批失败,非本空间
成员/停用/跨空间账号/已归属本空间逐条跳过并回传原因;归属指针与最近
活跃租户偏好一起改指本空间(登录路径优先读偏好,只改归属会被旧偏好
拉回),成员关系/角色/个人空间数据不动,可经空间切换器改回,非破坏性;
3. 收编成功者补跑自动入册(EnsureEmployeesForUsers 仅补空幂等),
同步部门自动匹配进名册;
4. 单条 rbac.member_home_adopted 审计(best-effort);路由 g.Owner() 限定,
与成员批量导入/Casdoor 同步同权限级别;
5. 收编依赖只引 repository 层(UserRepository/TenantMemberRepository),
避开 tenantMemberService→OrgCenterService→userService→memberService
的 DI 环;
6. 前端组织架构页新增「收编到本空间」入口(仅 hasRole('owner') 可见)+
预览确认弹窗(与 OA 同步弹窗同两段式交互);顺手补齐
OrgEmployee.wecom_userid 缺失的存量类型缺口(type-check 阻断项)。
测试:服务层新增收编落点+偏好/六类跳过/守卫 3 例;仓库层 sqlite 用例覆盖
NULL 归属兜底与停用/已归属排除;既有 org/member/casdoor/培训模板用例无回归。
374 lines
16 KiB
Go
374 lines
16 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"academy/internal/types"
|
|
"academy/internal/types/interfaces"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
// orgCenterRepository 组织中心(租户级共享组织架构)数据访问。
|
|
// 表: org_depts / org_employees / org_module_members(迁移 000137)。
|
|
// 企业培训(tr_depts/tr_members 时代)的查询语义在此平移;roles 展示字段
|
|
// 由指定 module_key 的绑定行联查得出。
|
|
type orgCenterRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewOrgCenterRepository constructs the org center repository.
|
|
func NewOrgCenterRepository(db *gorm.DB) interfaces.OrgCenterRepository {
|
|
return &orgCenterRepository{db: db}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 部门
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// ListDepts returns the tenant's department tree ordered by sort.
|
|
func (r *orgCenterRepository) ListDepts(ctx context.Context, tenantID uint64) ([]*types.OrgDept, error) {
|
|
var depts []*types.OrgDept
|
|
err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ?", tenantID).
|
|
Order("sort ASC, created_at ASC").
|
|
Find(&depts).Error
|
|
return depts, err
|
|
}
|
|
|
|
// CreateDept inserts a department node.
|
|
func (r *orgCenterRepository) CreateDept(ctx context.Context, dept *types.OrgDept) error {
|
|
return r.db.WithContext(ctx).Create(dept).Error
|
|
}
|
|
|
|
// UpdateDept updates mutable department fields.
|
|
func (r *orgCenterRepository) UpdateDept(ctx context.Context, dept *types.OrgDept) error {
|
|
return r.db.WithContext(ctx).Model(&types.OrgDept{}).
|
|
Where("tenant_id = ? AND id = ?", dept.TenantID, dept.ID).
|
|
Updates(map[string]interface{}{
|
|
"parent_id": dept.ParentID,
|
|
"name": dept.Name,
|
|
"code": dept.Code,
|
|
"sort": dept.Sort,
|
|
}).Error
|
|
}
|
|
|
|
// DeleteDept soft-deletes a department node.
|
|
func (r *orgCenterRepository) DeleteDept(ctx context.Context, tenantID uint64, id string) error {
|
|
return r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND id = ?", tenantID, id).
|
|
Delete(&types.OrgDept{}).Error
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 员工档案
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// employeeFilter 组装员工列表的公共过滤(租户/部门/关键词)。
|
|
// users/org_depts 联查在此一并挂上:keyword 需要按姓名/部门名过滤,且 Count
|
|
// 与列表共用同一过滤,联查必须两边一致(users/org_depts 对档案均为 1:1,
|
|
// 不影响 Count 语义)。
|
|
func (r *orgCenterRepository) employeeFilter(ctx context.Context, tenantID uint64, q *types.OrgListQuery) *gorm.DB {
|
|
tx := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
|
Where("org_employees.tenant_id = ?", tenantID).
|
|
Joins("LEFT JOIN users u ON u.id = org_employees.user_id").
|
|
Joins("LEFT JOIN org_depts dp ON dp.id = org_employees.dept_id AND dp.tenant_id = org_employees.tenant_id AND dp.deleted_at IS NULL")
|
|
if q != nil {
|
|
if q.DeptID != "" {
|
|
tx = tx.Where("org_employees.dept_id = ?", q.DeptID)
|
|
}
|
|
if q.Keyword != "" {
|
|
// 按姓名/工号/部门名/岗位模糊查找;姓名取真实姓名(display_name)
|
|
// 回退平台账号(username),与列表展示口径一致。
|
|
tx = tx.Where(
|
|
"org_employees.employee_no ILIKE ? OR COALESCE(NULLIF(u.display_name, ''), u.username, '') ILIKE ? "+
|
|
"OR COALESCE(dp.name, '') ILIKE ? OR org_employees.post ILIKE ? OR org_employees.user_id ILIKE ?",
|
|
"%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%", "%"+q.Keyword+"%")
|
|
}
|
|
}
|
|
return tx
|
|
}
|
|
|
|
// ListEmployees returns a page of employee profiles with joined display
|
|
// fields. moduleKey 非空时联查该模块的绑定行得出 roles 展示字段(培训列表传
|
|
// types.OrgModuleTraining;组织中心自身列表传空保持 '[]')。
|
|
func (r *orgCenterRepository) ListEmployees(ctx context.Context, tenantID uint64, moduleKey string, q *types.OrgListQuery) ([]*types.OrgEmployee, int64, error) {
|
|
filter := func() *gorm.DB {
|
|
return r.employeeFilter(ctx, tenantID, q)
|
|
}
|
|
var total int64
|
|
if err := filter().Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
page, pageSize := 1, 20
|
|
if q != nil {
|
|
if q.Page > 0 {
|
|
page = q.Page
|
|
}
|
|
if q.PageSize > 0 {
|
|
pageSize = q.PageSize
|
|
}
|
|
}
|
|
tx := filter().
|
|
// user_name 取真实姓名(display_name)优先:员工编号型 IdP(Casdoor)的
|
|
// username 存工号,真实姓名在 display_name(见 000143 迁移)。
|
|
Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name`)
|
|
if moduleKey != "" {
|
|
// 绑定行缺失时回退 '[]'(学员为全员隐式角色,无需绑定行)。
|
|
tx = tx.Select(`org_employees.*, COALESCE(NULLIF(u.display_name, ''), u.username, '') AS user_name, COALESCE(dp.name, '') AS dept_name,
|
|
COALESCE(mm.roles, '[]'::jsonb) AS roles`).
|
|
Joins("LEFT JOIN org_module_members mm ON mm.tenant_id = org_employees.tenant_id AND mm.employee_id = org_employees.id AND mm.module_key = ? AND mm.deleted_at IS NULL", moduleKey)
|
|
}
|
|
var employees []*types.OrgEmployee
|
|
// 新增成员置顶(时间倒序):最新建档/导入的员工排在列表最前。
|
|
err := tx.
|
|
Order("org_employees.created_at DESC").
|
|
Offset((page - 1) * pageSize).Limit(pageSize).
|
|
Find(&employees).Error
|
|
return employees, total, err
|
|
}
|
|
|
|
// GetEmployee fetches one employee profile by ID.
|
|
func (r *orgCenterRepository) GetEmployee(ctx context.Context, tenantID uint64, id string) (*types.OrgEmployee, error) {
|
|
var m types.OrgEmployee
|
|
if err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND id = ?", tenantID, id).
|
|
First(&m).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// GetEmployeeByUserID fetches one employee profile by the platform user ID.
|
|
func (r *orgCenterRepository) GetEmployeeByUserID(ctx context.Context, tenantID uint64, userID string) (*types.OrgEmployee, error) {
|
|
var m types.OrgEmployee
|
|
if err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND user_id = ?", tenantID, userID).
|
|
First(&m).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// InsertEmployeesIfAbsent 自动入册专用:成员加入空间时补建员工档案。
|
|
// 与 UpsertEmployees(导入语义,整行覆盖)不同,本方法只补空不覆盖——
|
|
// 已有档案的工号/部门仅在为空时用新值回填(如 Casdoor 后同步到部门),
|
|
// 人工维护过(或 OA 同步)的字段一律保留。
|
|
func (r *orgCenterRepository) InsertEmployeesIfAbsent(ctx context.Context, employees []*types.OrgEmployee) error {
|
|
if len(employees) == 0 {
|
|
return nil
|
|
}
|
|
return r.db.WithContext(ctx).
|
|
Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
|
DoUpdates: clause.Assignments(map[string]interface{}{
|
|
// 档案已有工号/部门时不覆盖(空串/空 id 视为未维护,由新值补齐)。
|
|
"employee_no": gorm.Expr("COALESCE(NULLIF(org_employees.employee_no, ''), EXCLUDED.employee_no)"),
|
|
"dept_id": gorm.Expr("COALESCE(NULLIF(org_employees.dept_id, ''), EXCLUDED.dept_id)"),
|
|
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
|
}),
|
|
}).
|
|
Create(&employees).Error
|
|
}
|
|
|
|
// UpsertEmployees bulk-imports employee profiles keyed by (tenant, user_id).
|
|
func (r *orgCenterRepository) UpsertEmployees(ctx context.Context, employees []*types.OrgEmployee) error {
|
|
if len(employees) == 0 {
|
|
return nil
|
|
}
|
|
return r.db.WithContext(ctx).
|
|
Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}},
|
|
DoUpdates: clause.Assignments(map[string]interface{}{
|
|
// 导入行未带工号时保留已有工号(空串不覆盖),与企微账号同款保护:
|
|
// 防止回填不到平台账号的导入行把原工号洗掉。
|
|
"employee_no": gorm.Expr("COALESCE(NULLIF(EXCLUDED.employee_no, ''), org_employees.employee_no)"),
|
|
"dept_id": gorm.Expr("EXCLUDED.dept_id"),
|
|
"post": gorm.Expr("EXCLUDED.post"),
|
|
"lecturer_rate": gorm.Expr("EXCLUDED.lecturer_rate"),
|
|
// 导入行未带企微账号时保留已有绑定(空串不覆盖),防止普通导入冲掉 OA 同步结果。
|
|
"wecom_userid": gorm.Expr("COALESCE(NULLIF(EXCLUDED.wecom_userid, ''), org_employees.wecom_userid)"),
|
|
"status": gorm.Expr("EXCLUDED.status"),
|
|
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
|
}),
|
|
}).
|
|
Create(&employees).Error
|
|
}
|
|
|
|
// UpdateEmployee updates mutable employee fields.
|
|
func (r *orgCenterRepository) UpdateEmployee(ctx context.Context, employee *types.OrgEmployee) error {
|
|
return r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
|
Where("tenant_id = ? AND id = ?", employee.TenantID, employee.ID).
|
|
Updates(map[string]interface{}{
|
|
"employee_no": employee.EmployeeNo,
|
|
"dept_id": employee.DeptID,
|
|
"post": employee.Post,
|
|
"lecturer_rate": employee.LecturerRate,
|
|
"wecom_userid": employee.WecomUserid,
|
|
"status": employee.Status,
|
|
}).Error
|
|
}
|
|
|
|
// DeleteEmployee soft-deletes an employee profile.
|
|
func (r *orgCenterRepository) DeleteEmployee(ctx context.Context, tenantID uint64, id string) error {
|
|
return r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND id = ?", tenantID, id).
|
|
Delete(&types.OrgEmployee{}).Error
|
|
}
|
|
|
|
// CountEmployees returns the tenant's active employee count.
|
|
func (r *orgCenterRepository) CountEmployees(ctx context.Context, tenantID uint64) (int64, error) {
|
|
var count int64
|
|
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
|
|
Where("tenant_id = ? AND status = 'active'", tenantID).
|
|
Count(&count).Error
|
|
return count, err
|
|
}
|
|
|
|
// ListTenantUsers lists the platform users of the tenant with their roster
|
|
// membership flag — the source for the employee-import user picker.
|
|
//
|
|
// 「平台用户」= 当前空间有 active 成员关系的用户,而不是主空间
|
|
// (users.tenant_id) 落在本空间的住户:通过邀请或 OIDC 同源自动加入的成员
|
|
// 主空间在别处,按主空间过滤会让选择器看不到他们(部署实测:共享空间
|
|
// 锚点看不到自动加入的成员)。名册 join 同样按被查询空间取数。
|
|
func (r *orgCenterRepository) ListTenantUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) {
|
|
var users []*types.TrainingUserInfo
|
|
err := r.db.WithContext(ctx).
|
|
Table("users u").
|
|
Select(`u.id, u.username, u.email, u.display_name,
|
|
u.dept_code, u.dept_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).
|
|
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
|
Order("u.created_at ASC").
|
|
Scan(&users).Error
|
|
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 的成员口径注释)。
|
|
func (r *orgCenterRepository) GetUsernamesByUserIDs(ctx context.Context, tenantID uint64, userIDs []string) (map[string]string, error) {
|
|
m := make(map[string]string, len(userIDs))
|
|
if len(userIDs) == 0 {
|
|
return m, nil
|
|
}
|
|
var users []*types.TrainingUserInfo
|
|
err := r.db.WithContext(ctx).
|
|
Table("users u").
|
|
Select("u.id, u.username").
|
|
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).
|
|
Where("u.id IN ?", userIDs).
|
|
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
|
Scan(&users).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, u := range users {
|
|
m[u.ID] = u.Username
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// GetRosterUserInfos resolves the roster-relevant user fields (平台账号 + Casdoor
|
|
// 同步部门) for the given user IDs within the tenant — source for auto-creating
|
|
// employee profiles when members join (EnsureEmployeesForUsers 的取数口径与
|
|
// GetUsernamesByUserIDs 一致:本空间 active 成员)。
|
|
func (r *orgCenterRepository) GetRosterUserInfos(ctx context.Context, tenantID uint64, userIDs []string) ([]*types.TrainingUserInfo, error) {
|
|
if len(userIDs) == 0 {
|
|
return nil, nil
|
|
}
|
|
var users []*types.TrainingUserInfo
|
|
err := r.db.WithContext(ctx).
|
|
Table("users u").
|
|
Select("u.id, u.username, u.dept_code, u.dept_name").
|
|
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).
|
|
Where("u.id IN ?", userIDs).
|
|
Where("u.is_active = TRUE AND u.deleted_at IS NULL").
|
|
Scan(&users).Error
|
|
return users, err
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 模块角色绑定
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// GetModuleMember fetches one module binding by employee.
|
|
func (r *orgCenterRepository) GetModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) (*types.OrgModuleMember, error) {
|
|
var m types.OrgModuleMember
|
|
if err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND module_key = ? AND employee_id = ? AND deleted_at IS NULL",
|
|
tenantID, moduleKey, employeeID).
|
|
First(&m).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// UpsertModuleMember inserts or refreshes one module binding keyed by
|
|
// (tenant, module_key, employee_id).
|
|
// 表上是部分唯一索引(WHERE deleted_at IS NULL),冲突目标必须带同一谓词,
|
|
// 否则 Postgres 报 42P10(no unique constraint matching ON CONFLICT)。
|
|
func (r *orgCenterRepository) UpsertModuleMember(ctx context.Context, member *types.OrgModuleMember) error {
|
|
return r.db.WithContext(ctx).
|
|
Clauses(clause.OnConflict{
|
|
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "module_key"}, {Name: "employee_id"}},
|
|
TargetWhere: clause.Where{Exprs: []clause.Expression{
|
|
gorm.Expr("deleted_at IS NULL"),
|
|
}},
|
|
DoUpdates: clause.Assignments(map[string]interface{}{
|
|
"roles": gorm.Expr("EXCLUDED.roles"),
|
|
"extra": gorm.Expr("EXCLUDED.extra"),
|
|
"updated_at": gorm.Expr("CURRENT_TIMESTAMP"),
|
|
}),
|
|
}).
|
|
Create(member).Error
|
|
}
|
|
|
|
// DeleteModuleMember soft-deletes one module binding.
|
|
func (r *orgCenterRepository) DeleteModuleMember(ctx context.Context, tenantID uint64, moduleKey, employeeID string) error {
|
|
return r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND module_key = ? AND employee_id = ?", tenantID, moduleKey, employeeID).
|
|
Delete(&types.OrgModuleMember{}).Error
|
|
}
|
|
|
|
// ListModuleMembers lists all bindings of one module.
|
|
func (r *orgCenterRepository) ListModuleMembers(ctx context.Context, tenantID uint64, moduleKey string) ([]*types.OrgModuleMember, error) {
|
|
var members []*types.OrgModuleMember
|
|
err := r.db.WithContext(ctx).
|
|
Where("tenant_id = ? AND module_key = ? AND deleted_at IS NULL", tenantID, moduleKey).
|
|
Order("created_at ASC").
|
|
Find(&members).Error
|
|
return members, err
|
|
}
|