From 5bc2e43f96e4306cb69aa2c568ea44318391bbce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Fri, 27 Dec 2024 22:03:44 -0500 Subject: [PATCH] add helper functions for dealing with group hierarchies --- models/group/group.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/models/group/group.go b/models/group/group.go index c4df33231d..668914dfd7 100644 --- a/models/group/group.go +++ b/models/group/group.go @@ -161,6 +161,42 @@ func FindGroupsByCond(ctx context.Context, cond builder.Cond, parentGroupID int6 Find(&groups) } +// GetParentGroupChain returns a slice containing a group and its ancestors +func GetParentGroupChain(ctx context.Context, groupID int64) (GroupList, error) { + groupList := make([]*Group, 0, 20) + currentGroupID := groupID + for { + if currentGroupID < 1 { + break + } + if len(groupList) >= 20 { + return nil, ErrGroupTooDeep{currentGroupID} + } + currentGroup, err := GetGroupByID(ctx, currentGroupID) + if err != nil { + return nil, err + } + groupList = append(groupList, currentGroup) + currentGroupID = currentGroup.ParentGroupID + } + return groupList, nil +} + +// ParentGroupCond returns a condition matching a group and its ancestors +func ParentGroupCond(idStr string, groupID int64) builder.Cond { + groupList, err := GetParentGroupChain(db.DefaultContext, groupID) + if err != nil { + log.Info("Error building group cond: %w", err) + return builder.NotIn(idStr) + } + return builder.In( + idStr, + util.SliceMap[*Group, int64](groupList, func(it *Group) int64 { + return it.ID + }), + ) +} + type ErrGroupNotExist struct { ID int64 }