package repository import ( "context" "next-terminal/server/common" "next-terminal/server/model" ) var DepartmentRepository = new(departmentRepository) type departmentRepository struct { baseRepository } func (r departmentRepository) FindAll(c context.Context) (o []model.Department, err error) { err = r.GetDB(c).Order("sort asc, name asc").Find(&o).Error return } func (r departmentRepository) Find(c context.Context, pageIndex, pageSize int, name, order, field string) (o []model.Department, total int64, err error) { db := r.GetDB(c).Model(&model.Department{}) if len(name) > 0 { db = db.Where("name like ?", "%"+name+"%") } err = db.Count(&total).Error if err != nil { return } if order == "" { order = "asc" } if field == "" { field = "sort" } err = db.Order(field + " " + order).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&o).Error return } func (r departmentRepository) FindById(c context.Context, id string) (o model.Department, err error) { err = r.GetDB(c).Where("id = ?", id).First(&o).Error return } func (r departmentRepository) FindByParentId(c context.Context, parentId string) (o []model.Department, err error) { db := r.GetDB(c) if parentId == "" { db = db.Where("parent_id = '' or parent_id is null") } else { db = db.Where("parent_id = ?", parentId) } err = db.Order("sort asc, name asc").Find(&o).Error return } func (r departmentRepository) Create(c context.Context, o *model.Department) error { o.Created = common.NowJsonTime() return r.GetDB(c).Create(o).Error } func (r departmentRepository) UpdateById(c context.Context, o *model.Department) error { return r.GetDB(c).Updates(o).Error } func (r departmentRepository) DeleteById(c context.Context, id string) error { return r.GetDB(c).Where("id = ?", id).Delete(&model.Department{}).Error } func (r departmentRepository) CountByParentId(c context.Context, parentId string) (total int64, err error) { err = r.GetDB(c).Model(&model.Department{}).Where("parent_id = ?", parentId).Count(&total).Error return } func (r departmentRepository) BuildTree(departments []model.Department) []map[string]interface{} { departmentMap := make(map[string][]map[string]interface{}) var roots []map[string]interface{} for _, dept := range departments { node := map[string]interface{}{ "title": dept.Name, "key": dept.ID, "value": dept.ID, "children": []map[string]interface{}{}, } if dept.ParentId == "" { roots = append(roots, node) } else { departmentMap[dept.ParentId] = append(departmentMap[dept.ParentId], node) } } var buildChildren func(nodes []map[string]interface{}) buildChildren = func(nodes []map[string]interface{}) { for i := range nodes { id := nodes[i]["key"].(string) if children, ok := departmentMap[id]; ok { nodes[i]["children"] = children buildChildren(children) } } } buildChildren(roots) return roots }