feat: complete IM group governance actions

This commit is contained in:
richjohnrambo
2026-08-21 16:34:55 +08:00
parent 21a5b97ac8
commit 77b19a8157
12 changed files with 981 additions and 17 deletions
+441
View File
@@ -25,6 +25,12 @@ import (
type sSysImGroup struct{}
const (
imGroupModeMember = "JRWPS"
imGroupModeAdmin = "JRWPASO"
imGroupModeOwner = "JRWPASDO"
)
func NewSysImGroup() *sSysImGroup {
return &sSysImGroup{}
}
@@ -523,6 +529,262 @@ func (s *sSysImGroup) Unmute(ctx context.Context, in *sysin.ImGroupUnmuteInp) (e
})
}
// JoinRequestApprove 通过IM入群申请
func (s *sSysImGroup) JoinRequestApprove(ctx context.Context, in *sysin.ImGroupJoinRequestResolveInp) (err error) {
if err = in.Filter(ctx); err != nil {
return
}
return s.resolveJoinRequest(ctx, in, consts.ImGroupRequestStatusAccepted)
}
// JoinRequestReject 拒绝IM入群申请
func (s *sSysImGroup) JoinRequestReject(ctx context.Context, in *sysin.ImGroupJoinRequestResolveInp) (err error) {
if err = in.Filter(ctx); err != nil {
return
}
return s.resolveJoinRequest(ctx, in, consts.ImGroupRequestStatusRejected)
}
func (s *sSysImGroup) resolveJoinRequest(ctx context.Context, in *sysin.ImGroupJoinRequestResolveInp, status string) (err error) {
db, _, err := resolveImTenantDB(ctx, in.TenantId)
if err != nil {
return err
}
actor := contexts.GetUserId(ctx)
requestId := gctx.CtxId(ctx)
if requestId == "" {
requestId = guid.S()
}
now := gtime.Now()
return db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
if err := s.ensureActiveGroup(ctx, tx, in.Topic); err != nil {
return err
}
before, txErr := s.groupJoinRequestSnapshot(ctx, tx, in.Topic, in.RequestId)
if txErr != nil {
return txErr
}
if before == nil {
return gerror.New("入群申请不存在")
}
if before["status"].String() != consts.ImGroupRequestStatusPending {
return gerror.New("入群申请已处理")
}
applicantUserId := before["applicant_user_id"].Int64()
if status == consts.ImGroupRequestStatusAccepted {
if txErr = s.upsertGroupSubscription(ctx, tx, in.Topic, applicantUserId, imGroupModeMember, now); txErr != nil {
return txErr
}
if txErr = s.upsertGroupMember(ctx, tx, in.Topic, applicantUserId, consts.ImGroupRoleMember, "approval", actor, now); txErr != nil {
return txErr
}
}
result, txErr := tx.Exec(`UPDATE im_group_join_requests
SET status=?,reject_reason=?,handled_by=?,handled_at=?,updated_at=?,version=version+1
WHERE topic=? AND request_id=? AND status=?`,
status, in.RejectReason, actor, now, now, in.Topic, in.RequestId, consts.ImGroupRequestStatusPending)
if txErr != nil {
return txErr
}
if affected, _ := result.RowsAffected(); affected == 0 {
return gerror.New("入群申请已处理")
}
if txErr = s.recountGroupMembers(ctx, tx, in.Topic); txErr != nil {
return txErr
}
after, txErr := s.groupJoinRequestSnapshot(ctx, tx, in.Topic, in.RequestId)
if txErr != nil {
return txErr
}
action := "join_request_reject"
if status == consts.ImGroupRequestStatusAccepted {
action = "join_request_accept"
}
if txErr = s.insertGroupAdminLog(ctx, tx, in.Topic, actor, applicantUserId, action, "join_request", in.RequestId, recordMap(before), recordMap(after), requestId); txErr != nil {
return txErr
}
return s.insertGroupEvent(ctx, tx, in.Topic, actor, "group.join_request."+status, g.Map{
"topic": in.Topic, "request_id": in.RequestId, "applicant_user_id": applicantUserId, "status": status, "request_id_admin": requestId,
})
})
}
// RoleUpdate 更新IM群成员角色
func (s *sSysImGroup) RoleUpdate(ctx context.Context, in *sysin.ImGroupRoleUpdateInp) (err error) {
if err = in.Filter(ctx); err != nil {
return
}
if in.Role != consts.ImGroupRoleAdmin && in.Role != consts.ImGroupRoleMember {
return gerror.New("只能设置管理员或普通成员")
}
db, _, err := resolveImTenantDB(ctx, in.TenantId)
if err != nil {
return err
}
actor := contexts.GetUserId(ctx)
requestId := gctx.CtxId(ctx)
if requestId == "" {
requestId = guid.S()
}
modeGiven := imGroupModeMember
action := "member_role_member"
if in.Role == consts.ImGroupRoleAdmin {
modeGiven = imGroupModeAdmin
action = "member_role_admin"
}
now := gtime.Now()
return db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
if err := s.ensureActiveGroup(ctx, tx, in.Topic); err != nil {
return err
}
before, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
if before == nil || before["member_status"].String() != consts.ImGroupMemberStatusActive {
return gerror.New("成员不在群内或不是正常状态")
}
if before["role"].String() == consts.ImGroupRoleOwner {
return gerror.New("群主角色请通过群主转让处理")
}
if in.Role == consts.ImGroupRoleAdmin {
if txErr = s.ensureAdminLimit(ctx, tx, in.Topic, in.UserId); txErr != nil {
return txErr
}
}
subResult, txErr := tx.Exec(`UPDATE im_subscriptions SET modegiven=?,updatedat=?
WHERE topic=? AND userid=? AND deletedat IS NULL`, modeGiven, now, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
if affected, _ := subResult.RowsAffected(); affected == 0 {
return gerror.New("成员通信订阅不存在")
}
result, txErr := tx.Exec(`UPDATE im_group_members
SET role=?,version=version+1,updated_at=?
WHERE topic=? AND user_id=? AND member_status=?`,
in.Role, now, in.Topic, in.UserId, consts.ImGroupMemberStatusActive)
if txErr != nil {
return txErr
}
if affected, _ := result.RowsAffected(); affected == 0 {
return gerror.New("成员不在群内或不是正常状态")
}
after, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
if txErr = s.insertGroupAdminLog(ctx, tx, in.Topic, actor, in.UserId, action, "member", fmt.Sprintf("%d", in.UserId), recordMap(before), recordMap(after), requestId); txErr != nil {
return txErr
}
return s.insertGroupEvent(ctx, tx, in.Topic, actor, "group.role.updated", g.Map{
"topic": in.Topic, "user_id": in.UserId, "role": in.Role, "request_id": requestId,
})
})
}
// OwnerTransfer 转让IM群主
func (s *sSysImGroup) OwnerTransfer(ctx context.Context, in *sysin.ImGroupOwnerTransferInp) (err error) {
if err = in.Filter(ctx); err != nil {
return
}
db, _, err := resolveImTenantDB(ctx, in.TenantId)
if err != nil {
return err
}
actor := contexts.GetUserId(ctx)
requestId := gctx.CtxId(ctx)
if requestId == "" {
requestId = guid.S()
}
now := gtime.Now()
return db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
beforeGroup, txErr := s.groupGovernanceSnapshot(ctx, tx, in.Topic)
if txErr != nil {
return txErr
}
if beforeGroup == nil {
return gerror.New("群治理配置不存在")
}
if beforeGroup["group_status"].String() == consts.ImGroupStatusDissolved {
return gerror.New("已解散群不能转让群主")
}
previousOwner := beforeGroup["owner_user_id"].Int64()
if previousOwner <= 0 {
return gerror.New("原群主不存在")
}
if previousOwner == in.UserId {
return gerror.New("新群主不能与原群主相同")
}
if txErr = s.ensureActiveGroupMember(ctx, tx, in.Topic, previousOwner); txErr != nil {
return txErr
}
if txErr = s.ensureActiveGroupMember(ctx, tx, in.Topic, in.UserId); txErr != nil {
return txErr
}
beforeOld, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, previousOwner)
if txErr != nil {
return txErr
}
beforeNew, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
oldSubResult, txErr := tx.Exec(`UPDATE im_subscriptions SET modegiven=?,updatedat=?
WHERE topic=? AND userid=? AND deletedat IS NULL`, imGroupModeAdmin, now, in.Topic, previousOwner)
if txErr != nil {
return txErr
}
if affected, _ := oldSubResult.RowsAffected(); affected == 0 {
return gerror.New("原群主通信订阅不存在")
}
if _, txErr = tx.Exec(`UPDATE im_group_members SET role=?,version=version+1,updated_at=?
WHERE topic=? AND user_id=? AND member_status=?`, consts.ImGroupRoleAdmin, now, in.Topic, previousOwner, consts.ImGroupMemberStatusActive); txErr != nil {
return txErr
}
newSubResult, txErr := tx.Exec(`UPDATE im_subscriptions SET modegiven=?,updatedat=?
WHERE topic=? AND userid=? AND deletedat IS NULL`, imGroupModeOwner, now, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
if affected, _ := newSubResult.RowsAffected(); affected == 0 {
return gerror.New("新群主通信订阅不存在")
}
if _, txErr = tx.Exec(`UPDATE im_group_members SET role=?,version=version+1,updated_at=?
WHERE topic=? AND user_id=? AND member_status=?`, consts.ImGroupRoleOwner, now, in.Topic, in.UserId, consts.ImGroupMemberStatusActive); txErr != nil {
return txErr
}
if _, txErr = tx.Exec(`UPDATE im_topics SET owner=?,updatedat=? WHERE name=?`, in.UserId, now, in.Topic); txErr != nil {
return txErr
}
if _, txErr = tx.Exec(`UPDATE im_group_settings SET owner_user_id=?,version=version+1,updated_at=? WHERE topic=?`, in.UserId, now, in.Topic); txErr != nil {
return txErr
}
afterGroup, txErr := s.groupGovernanceSnapshot(ctx, tx, in.Topic)
if txErr != nil {
return txErr
}
afterOld, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, previousOwner)
if txErr != nil {
return txErr
}
afterNew, txErr := s.groupMemberSnapshot(ctx, tx, in.Topic, in.UserId)
if txErr != nil {
return txErr
}
if txErr = s.insertGroupAdminLog(ctx, tx, in.Topic, actor, in.UserId, "owner_transfer", "group", in.Topic, g.Map{
"group": recordMap(beforeGroup), "previous_owner": recordMap(beforeOld), "new_owner": recordMap(beforeNew),
}, g.Map{
"group": recordMap(afterGroup), "previous_owner": recordMap(afterOld), "new_owner": recordMap(afterNew),
}, requestId); txErr != nil {
return txErr
}
return s.insertGroupEvent(ctx, tx, in.Topic, actor, "group.owner.transferred", g.Map{
"topic": in.Topic, "previous_owner": previousOwner, "owner": in.UserId, "request_id": requestId,
})
})
}
func (s *sSysImGroup) groupGovernanceSnapshot(ctx context.Context, tx gdb.TX, topic string) (res gdb.Record, err error) {
return tx.Model("im_group_settings").Safe().Ctx(ctx).
Fields(
@@ -535,6 +797,41 @@ func (s *sSysImGroup) groupGovernanceSnapshot(ctx context.Context, tx gdb.TX, to
One()
}
func (s *sSysImGroup) groupJoinRequestSnapshot(ctx context.Context, tx gdb.TX, topic string, requestId string) (res gdb.Record, err error) {
return tx.Model("im_group_join_requests").Safe().Ctx(ctx).
Where("topic", topic).
Where("request_id", requestId).
One()
}
func (s *sSysImGroup) groupMemberSnapshot(ctx context.Context, tx gdb.TX, topic string, userId int64) (res gdb.Record, err error) {
return tx.Model("im_group_members").Safe().Ctx(ctx).
Where("topic", topic).
Where("user_id", userId).
One()
}
func (s *sSysImGroup) groupFileSnapshot(ctx context.Context, tx gdb.TX, topic string, groupFileId string) (res gdb.Record, err error) {
return tx.Model("im_group_files").Safe().Ctx(ctx).
Where("topic", topic).
Where("group_file_id", groupFileId).
One()
}
func (s *sSysImGroup) ensureActiveGroup(ctx context.Context, tx gdb.TX, topic string) error {
status, err := tx.Model("im_group_settings").Safe().Ctx(ctx).Where("topic", topic).Value("group_status")
if err != nil {
return err
}
if status.IsNil() {
return gerror.New("群治理配置不存在")
}
if status.String() == consts.ImGroupStatusDissolved {
return gerror.New("已解散群不能执行该操作")
}
return nil
}
func (s *sSysImGroup) groupMuteSnapshot(ctx context.Context, tx gdb.TX, topic string, userId int64) (res gdb.Record, err error) {
return tx.Model("im_group_mutes").Safe().Ctx(ctx).
Fields(
@@ -561,6 +858,69 @@ func (s *sSysImGroup) ensureActiveGroupMember(ctx context.Context, tx gdb.TX, to
return nil
}
func (s *sSysImGroup) ensureAdminLimit(ctx context.Context, tx gdb.TX, topic string, userId int64) error {
currentRole, err := tx.Model("im_group_members").Safe().Ctx(ctx).
Where("topic", topic).
Where("user_id", userId).
Where("member_status", consts.ImGroupMemberStatusActive).
Value("role")
if err != nil {
return err
}
if currentRole.String() == consts.ImGroupRoleAdmin {
return nil
}
maxAdminCount, err := tx.Model("im_group_settings").Safe().Ctx(ctx).Where("topic", topic).Value("max_admin_count")
if err != nil {
return err
}
if maxAdminCount.Int() <= 0 {
return nil
}
adminCount, err := tx.Model("im_group_members").Safe().Ctx(ctx).
Where("topic", topic).
Where("role", consts.ImGroupRoleAdmin).
Where("member_status", consts.ImGroupMemberStatusActive).
Count()
if err != nil {
return err
}
if adminCount >= maxAdminCount.Int() {
return gerror.New("群管理员数量已达上限")
}
return nil
}
func (s *sSysImGroup) upsertGroupSubscription(ctx context.Context, tx gdb.TX, topic string, userId int64, modeGiven string, now *gtime.Time) error {
_, err := tx.Exec(`INSERT INTO im_subscriptions(createdat,updatedat,deletedat,userid,topic,modewant,modegiven,private)
VALUES(?,?,NULL,?,?,?,?,CAST('{}' AS JSON))
ON DUPLICATE KEY UPDATE createdat=VALUES(createdat),updatedat=VALUES(updatedat),deletedat=NULL,
modewant=VALUES(modewant),modegiven=VALUES(modegiven),delid=0,recvseqid=0,readseqid=0`,
now, now, userId, topic, imGroupModeMember, modeGiven)
return err
}
func (s *sSysImGroup) upsertGroupMember(ctx context.Context, tx gdb.TX, topic string, userId int64, role string, joinSource string, joinedBy int64, now *gtime.Time) error {
_, err := tx.Exec(`INSERT INTO im_group_members(topic,user_id,role,member_status,join_source,joined_by,joined_at,version,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE role=VALUES(role),member_status=VALUES(member_status),join_source=VALUES(join_source),
joined_by=VALUES(joined_by),joined_at=VALUES(joined_at),left_at=NULL,removed_by=NULL,version=version+1,updated_at=VALUES(updated_at)`,
topic, userId, role, consts.ImGroupMemberStatusActive, joinSource, joinedBy, now, 1, now, now)
return err
}
func (s *sSysImGroup) recountGroupMembers(ctx context.Context, tx gdb.TX, topic string) error {
if _, err := tx.Exec(`UPDATE im_group_settings
SET member_count=(SELECT COUNT(*) FROM im_group_members WHERE topic=? AND member_status=?),updated_at=CURRENT_TIMESTAMP(3)
WHERE topic=?`, topic, consts.ImGroupMemberStatusActive, topic); err != nil {
return err
}
_, err := tx.Exec(`UPDATE im_topics
SET subcnt=(SELECT COUNT(*) FROM im_subscriptions WHERE topic=? AND deletedat IS NULL),updatedat=CURRENT_TIMESTAMP(3)
WHERE name=?`, topic, topic)
return err
}
func recordMap(record gdb.Record) any {
if record == nil {
return nil
@@ -619,6 +979,87 @@ func (s *sSysImGroup) JoinRequestList(ctx context.Context, in *sysin.ImGroupJoin
return
}
// FileList 获取IM群文件列表
func (s *sSysImGroup) FileList(ctx context.Context, in *sysin.ImGroupFileListInp) (list []*sysin.ImGroupFileListModel, totalCount int, err error) {
if err = in.Filter(ctx); err != nil {
return
}
db, _, err := resolveImTenantDB(ctx, in.TenantId)
if err != nil {
return
}
mod := db.Model("im_group_files").Safe().Ctx(ctx).Where("topic", in.Topic)
if in.Status != "" {
mod = mod.Where("status", in.Status)
}
if in.FileType != "" {
mod = mod.Where("file_type", in.FileType)
}
if in.FileName != "" {
mod = mod.WhereLike("file_name", "%"+in.FileName+"%")
}
if in.UploaderId > 0 {
mod = mod.Where("uploader_id", in.UploaderId)
}
mod = mod.Page(in.Page, in.PerPage).OrderDesc("id")
if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
err = gerror.Wrap(err, "获取IM群文件列表失败,请稍后重试!")
}
return
}
// FileDelete 删除IM群文件
func (s *sSysImGroup) FileDelete(ctx context.Context, in *sysin.ImGroupFileDeleteInp) (err error) {
if err = in.Filter(ctx); err != nil {
return
}
db, _, err := resolveImTenantDB(ctx, in.TenantId)
if err != nil {
return err
}
actor := contexts.GetUserId(ctx)
requestId := gctx.CtxId(ctx)
if requestId == "" {
requestId = guid.S()
}
now := gtime.Now()
return db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
if err := s.ensureActiveGroup(ctx, tx, in.Topic); err != nil {
return err
}
before, txErr := s.groupFileSnapshot(ctx, tx, in.Topic, in.GroupFileId)
if txErr != nil {
return txErr
}
if before == nil {
return gerror.New("群文件不存在")
}
if before["status"].String() == consts.ImGroupFileStatusDeleted {
return gerror.New("群文件已删除")
}
result, txErr := tx.Exec(`UPDATE im_group_files
SET status=?,deleted_by=?,deleted_at=?,updated_at=?
WHERE topic=? AND group_file_id=? AND status<>?`,
consts.ImGroupFileStatusDeleted, actor, now, now, in.Topic, in.GroupFileId, consts.ImGroupFileStatusDeleted)
if txErr != nil {
return txErr
}
if affected, _ := result.RowsAffected(); affected == 0 {
return gerror.New("群文件已删除")
}
after, txErr := s.groupFileSnapshot(ctx, tx, in.Topic, in.GroupFileId)
if txErr != nil {
return txErr
}
if txErr = s.insertGroupAdminLog(ctx, tx, in.Topic, actor, before["uploader_id"].Int64(), "group_file_delete", "group_file", in.GroupFileId, recordMap(before), recordMap(after), requestId); txErr != nil {
return txErr
}
return s.insertGroupEvent(ctx, tx, in.Topic, actor, "group.file.deleted", g.Map{
"topic": in.Topic, "group_file_id": in.GroupFileId, "file_id": before["file_id"].String(), "request_id": requestId,
})
})
}
// InvitationList 获取IM群邀请列表
func (s *sSysImGroup) InvitationList(ctx context.Context, in *sysin.ImGroupInvitationListInp) (list []*sysin.ImGroupInvitationListModel, totalCount int, err error) {
if err = in.Filter(ctx); err != nil {