feat(platform): align account user membership

This commit is contained in:
2026-06-06 02:00:15 +08:00
parent fbb405a7a0
commit 706c706ee4
6 changed files with 105 additions and 37 deletions
+41 -1
View File
@@ -100,6 +100,46 @@ func (r *AccountRepo) AddUserToAccount(ctx context.Context, accountID, userID ui
return r.db.WithContext(ctx).Create(&au).Error
}
// UpsertAccountUser creates or updates an AccountUser membership.
// Reference: Chatwoot Platform::Api::V1::AccountUsersController#create uses
// account.account_users.find_or_initialize_by(user_id: ...).update!(params).
func (r *AccountRepo) UpsertAccountUser(ctx context.Context, accountID, userID uint, role *string) (*model.AccountUser, error) {
var au model.AccountUser
err := r.db.WithContext(ctx).
Where("account_id = ? AND user_id = ?", accountID, userID).
First(&au).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
if err == gorm.ErrRecordNotFound {
au = model.AccountUser{
AccountID: accountID,
UserID: userID,
Role: "agent",
Availability: "offline",
AutoOffline: true,
}
}
if role != nil && *role != "" {
au.Role = *role
}
if err == gorm.ErrRecordNotFound {
if err := r.db.WithContext(ctx).Create(&au).Error; err != nil {
return nil, err
}
return &au, nil
}
if role != nil {
if err := r.db.WithContext(ctx).Model(&au).Update("role", au.Role).Error; err != nil {
return nil, err
}
}
return &au, nil
}
// RemoveUserFromAccount deletes an AccountUser association.
func (r *AccountRepo) RemoveUserFromAccount(ctx context.Context, accountID, userID uint) error {
return r.db.WithContext(ctx).Exec(
@@ -171,4 +211,4 @@ func (r *AccountRepo) FindAccountUserByUserAndAccount(ctx context.Context, accou
return nil, err
}
return &au, nil
}
}