73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
package repository
|
|
|
|
import (
|
|
"seeyon-filesystem/config"
|
|
"seeyon-filesystem/model"
|
|
)
|
|
|
|
// DepartmentRepository 部门数据访问
|
|
type DepartmentRepository struct{}
|
|
|
|
func NewDepartmentRepository() *DepartmentRepository {
|
|
return &DepartmentRepository{}
|
|
}
|
|
|
|
// Create 创建部门
|
|
func (r *DepartmentRepository) Create(dept *model.Department) error {
|
|
return config.DB.Create(dept).Error
|
|
}
|
|
|
|
// FindByID 根据ID查找部门
|
|
func (r *DepartmentRepository) FindByID(id uint64) (*model.Department, error) {
|
|
var dept model.Department
|
|
err := config.DB.First(&dept, id).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &dept, nil
|
|
}
|
|
|
|
// List 查询所有部门
|
|
func (r *DepartmentRepository) List() ([]model.Department, error) {
|
|
var depts []model.Department
|
|
err := config.DB.Order("sort_order ASC, id ASC").Find(&depts).Error
|
|
return depts, err
|
|
}
|
|
|
|
// ListByParent 查询子部门
|
|
func (r *DepartmentRepository) ListByParent(parentID uint64) ([]model.Department, error) {
|
|
var depts []model.Department
|
|
err := config.DB.Where("parent_id = ?", parentID).Order("sort_order ASC, id ASC").Find(&depts).Error
|
|
return depts, err
|
|
}
|
|
|
|
// Update 更新部门
|
|
func (r *DepartmentRepository) Update(dept *model.Department) error {
|
|
return config.DB.Save(dept).Error
|
|
}
|
|
|
|
// Delete 删除部门
|
|
func (r *DepartmentRepository) Delete(id uint64) error {
|
|
// 检查是否有子部门
|
|
var count int64
|
|
config.DB.Model(&model.Department{}).Where("parent_id = ?", id).Count(&count)
|
|
if count > 0 {
|
|
return nil // 有子部门不允许删除, 由service层处理错误
|
|
}
|
|
return config.DB.Delete(&model.Department{}, id).Error
|
|
}
|
|
|
|
// HasChildren 检查是否有子部门
|
|
func (r *DepartmentRepository) HasChildren(id uint64) (bool, error) {
|
|
var count int64
|
|
err := config.DB.Model(&model.Department{}).Where("parent_id = ?", id).Count(&count).Error
|
|
return count > 0, err
|
|
}
|
|
|
|
// CountUsers 统计部门下的用户数
|
|
func (r *DepartmentRepository) CountUsers(deptID uint64) (int64, error) {
|
|
var count int64
|
|
err := config.DB.Model(&model.User{}).Where("dept_id = ?", deptID).Count(&count).Error
|
|
return count, err
|
|
}
|