admin: add create-user dialog and API
Some checks failed
build quyun / Build (push) Failing after 1m23s

This commit is contained in:
2025-12-22 15:57:32 +08:00
parent 4704cf6949
commit 859d628cd6
5 changed files with 139 additions and 0 deletions

View File

@@ -477,3 +477,53 @@ func (m *users) SetPhone(ctx context.Context, userID int64, phone string) error
}
return nil
}
// CreateByPhone 管理端通过手机号创建新用户(手机号必填,昵称可选)。
func (m *users) CreateByPhone(ctx context.Context, phone, username string) (*models.User, error) {
phone = strings.TrimSpace(phone)
if phone == "" {
return nil, errors.New("手机号不能为空")
}
if len(phone) != 11 {
return nil, errors.New("手机号必须为 11 位数字")
}
for _, r := range phone {
if r < '0' || r > '9' {
return nil, errors.New("手机号必须为 11 位数字")
}
}
_, err := m.FindByPhone(ctx, phone)
if err == nil {
return nil, errors.New("手机号已被其他用户占用")
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrap(err, "failed to check phone uniqueness")
}
openID := "phone:" + phone
tbl, query := models.UserQuery.QueryContext(ctx)
if _, err := query.Where(tbl.OpenID.Eq(openID)).First(); err == nil {
return nil, errors.New("用户已存在")
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrap(err, "failed to check open_id uniqueness")
}
username = strings.TrimSpace(username)
if username == "" {
username = "用户" + phone[len(phone)-4:]
}
user := &models.User{
OpenID: openID,
Username: username,
Phone: phone,
Balance: 0,
Avatar: "",
}
if err := _db.WithContext(ctx).Omit("metas", "auth_token").Create(user).Error; err != nil {
return nil, errors.Wrap(err, "failed to create user")
}
return user, nil
}