feat(invitations): implement pending invitations feature with polling and dialog

Added functionality for managing pending invitations, including a polling mechanism to update the invitation count in real-time. Introduced a new dialog component for users to view and respond to their invitations without navigating away from their current context. Updated API endpoints for fetching and managing invitations, and enhanced the user interface with relevant internationalization support.

Refs: #1303
This commit is contained in:
wizardchen
2026-05-17 21:19:59 +08:00
committed by lyingbug
parent 3bb0d6d763
commit 884ac44283
36 changed files with 4378 additions and 440 deletions
+42
View File
@@ -0,0 +1,42 @@
package handler
import (
"fmt"
"strconv"
"strings"
"github.com/gin-gonic/gin"
apperrors "github.com/Tencent/WeKnora/internal/errors"
)
const (
defaultListPageSize = 20
maxListPageSize = 100
)
// parseListPagination parses ?page and ?page_size for tenant-scoped list
// endpoints. Omitted keys default to page=1 and page_size=20. A present but
// malformed or out-of-range value yields a validation error on the context.
func parseListPagination(c *gin.Context) (page, pageSize int, ok bool) {
page = 1
pageSize = defaultListPageSize
if s := strings.TrimSpace(c.Query("page")); s != "" {
p, err := strconv.Atoi(s)
if err != nil || p < 1 {
c.Error(apperrors.NewValidationError("page must be a positive integer"))
return 0, 0, false
}
page = p
}
if s := strings.TrimSpace(c.Query("page_size")); s != "" {
ps, err := strconv.Atoi(s)
if err != nil || ps < 1 || ps > maxListPageSize {
c.Error(apperrors.NewValidationError(fmt.Sprintf("page_size must be between 1 and %d", maxListPageSize)))
return 0, 0, false
}
pageSize = ps
}
return page, pageSize, true
}
+506
View File
@@ -0,0 +1,506 @@
package handler
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// TenantInvitationHandler exposes the tenant-scoped CRUD on the
// `tenant_invitations` table plus the user-self-service inbox endpoints
// (/me/invitations*). Route-level RBAC: tenant routes are Owner-gated
// (POST/DELETE) or Viewer-gated (GET); inbox routes only require
// authentication (the service enforces "only invitee can act").
type TenantInvitationHandler struct {
invitationService interfaces.TenantInvitationService
userService interfaces.UserService
tenantService interfaces.TenantService
}
// NewTenantInvitationHandler wires the dependencies. tenantService is
// used to hydrate tenant names in the inbox view so the invitee sees
// "join Foo Workspace" instead of a raw numeric tenant id.
func NewTenantInvitationHandler(
invitationService interfaces.TenantInvitationService,
userService interfaces.UserService,
tenantService interfaces.TenantService,
) *TenantInvitationHandler {
return &TenantInvitationHandler{
invitationService: invitationService,
userService: userService,
tenantService: tenantService,
}
}
// createInvitationRequest is the JSON body for POST /tenants/:id/invitations.
// Email is the user-facing identifier; the handler resolves it to a
// User row before delegating to the service. The optional Message is
// surfaced in the invitee's inbox.
type createInvitationRequest struct {
Email string `json:"email" binding:"required,email"`
Role types.TenantRole `json:"role" binding:"required"`
Message string `json:"message"`
}
// parseInvitationIDFromPath reads :inv_id off the gin context.
func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
raw := strings.TrimSpace(c.Param("inv_id"))
if raw == "" {
c.Error(apperrors.NewValidationError("invitation id is required"))
return 0, false
}
v, err := strconv.ParseUint(raw, 10, 64)
if err != nil || v == 0 {
c.Error(apperrors.NewValidationError("invitation id must be a positive integer"))
return 0, false
}
return v, true
}
// projectInvitation hydrates a single TenantInvitation row into the
// API response shape. Inviter / invitee user fields and the tenant
// name are filled best-effort: a missing row degrades to the bare id
// rather than dropping the response. usersByID and tenantsByID let the
// caller batch the lookups when projecting a list.
func projectInvitation(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
tenantsByID map[uint64]*types.Tenant,
) types.TenantInvitationResponse {
resp := types.TenantInvitationResponse{
ID: inv.ID,
TenantID: inv.TenantID,
InviteeUserID: inv.InviteeUserID,
InvitedBy: inv.InvitedBy,
Role: inv.Role,
Status: inv.Status,
Message: inv.Message,
ExpiresAt: inv.ExpiresAt,
RespondedAt: inv.RespondedAt,
CreatedAt: inv.CreatedAt,
}
if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
resp.InviteeEmail = u.Email
resp.InviteeName = u.Username
}
if inv.InvitedBy != nil {
if u, ok := usersByID[*inv.InvitedBy]; ok && u != nil {
resp.InviterEmail = u.Email
resp.InviterName = u.Username
}
}
if t, ok := tenantsByID[inv.TenantID]; ok && t != nil {
resp.TenantName = t.Name
}
return resp
}
// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
// Best-effort: a transient lookup failure logs and returns an empty
// map so the projection falls back to ids.
func (h *TenantInvitationHandler) hydrateUsers(c *gin.Context, invs []*types.TenantInvitation) map[string]*types.User {
if len(invs) == 0 {
return map[string]*types.User{}
}
idSet := make(map[string]struct{}, len(invs)*2)
for _, inv := range invs {
idSet[inv.InviteeUserID] = struct{}{}
if inv.InvitedBy != nil {
idSet[*inv.InvitedBy] = struct{}{}
}
}
ids := make([]string, 0, len(idSet))
for id := range idSet {
ids = append(ids, id)
}
users, err := h.userService.GetUsersByIDs(c.Request.Context(), ids)
if err != nil {
logger.Warnf(c.Request.Context(), "invitation list: batch user hydrate failed: %v", err)
return map[string]*types.User{}
}
return users
}
// hydrateTenants is the same idea over the distinct tenant_ids touched
// by `invs`. Used by the /me inbox view where invitations span tenants.
func (h *TenantInvitationHandler) hydrateTenants(c *gin.Context, invs []*types.TenantInvitation) map[uint64]*types.Tenant {
if len(invs) == 0 || h.tenantService == nil {
return map[uint64]*types.Tenant{}
}
idSet := make(map[uint64]struct{}, len(invs))
for _, inv := range invs {
idSet[inv.TenantID] = struct{}{}
}
ids := make([]uint64, 0, len(idSet))
for id := range idSet {
ids = append(ids, id)
}
tenants, err := h.tenantService.GetTenantsByIDs(c.Request.Context(), ids)
if err != nil {
logger.Warnf(c.Request.Context(), "invitation list: batch tenant hydrate failed: %v", err)
return map[uint64]*types.Tenant{}
}
return tenants
}
// ListTenantInvitations godoc
// @Summary 列出租户邀请
// @Description 按 tenant 列出待接受 / 历史邀请。query include_terminal=true 时附带 accepted/declined/revoked/expired。
// @Tags 租户邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param include_terminal query bool false "是否包含终止态行(默认 false)"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量" default(20)
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations [get]
func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
page, pageSize, ok := parseListPagination(c)
if !ok {
return
}
rows, total, err := h.invitationService.ListTenantInvitationsPage(ctx, tenantID, includeTerminal, page, pageSize)
if err != nil {
logger.Errorf(ctx, "ListTenantInvitationsPage failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
return
}
usersByID := h.hydrateUsers(c, rows)
resp := make([]types.TenantInvitationResponse, 0, len(rows))
for _, inv := range rows {
// Within the tenant view we don't bother hydrating tenant name
// (the caller already knows the tenant). Pass an empty map.
resp = append(resp, projectInvitation(inv, usersByID, nil))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"invitations": resp,
"total": total,
"page": page,
"page_size": pageSize,
},
})
}
// CreateInvitation godoc
// @Summary 发出租户邀请
// @Description Owner 通过邮箱邀请已注册用户加入当前租户;被邀请人需要在 /me/invitations 接受后才会成为成员。
// @Tags 租户邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param request body createInvitationRequest true "邀请请求"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations [post]
func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
var req createInvitationRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
return
}
if !req.Role.IsValid() {
c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
return
}
user, err := h.userService.GetUserByEmail(ctx, strings.TrimSpace(req.Email))
if err != nil {
if errors.Is(err, apprepo.ErrUserNotFound) {
c.Error(apperrors.NewNotFoundError(
"user with this email is not registered; ask them to sign up first"))
return
}
logger.Errorf(ctx, "GetUserByEmail failed: email=%s err=%v",
secutils.SanitizeForLog(req.Email), err)
c.Error(apperrors.NewInternalServerError("failed to look up user").WithDetails(err.Error()))
return
}
caller, _ := types.UserIDFromContext(ctx)
var invitedBy *string
if caller != "" && !types.IsSyntheticUserID(caller) {
invitedBy = &caller
}
inv, err := h.invitationService.Create(ctx, tenantID, user.ID, req.Role, invitedBy, req.Message)
if err != nil {
switch {
case errors.Is(err, service.ErrInvalidTenantRole):
c.Error(apperrors.NewValidationError(err.Error()))
case errors.Is(err, service.ErrPendingInvitationExists):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrAlreadyMember):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "CreateInvitation failed: user=%s tenant=%d err=%v",
user.ID, tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to create invitation").WithDetails(err.Error()))
}
return
}
usersByID := map[string]*types.User{user.ID: user}
if invitedBy != nil {
// Best-effort hydrate inviter too. Errors are swallowed —
// the response degrades to just the invitee fields.
if u, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && u != nil {
usersByID[u.ID] = u
}
}
resp := projectInvitation(inv, usersByID, nil)
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": resp,
})
}
// RevokeInvitation godoc
// @Summary 撤销待接受邀请
// @Description Owner 取消一条还在 pending 的邀请;已 accepted/declined/revoked/expired 的行不可再撤销。
// @Tags 租户邀请
// @Produce json
// @Param id path string true "租户 ID"
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invitations/{inv_id} [delete]
func (h *TenantInvitationHandler) RevokeInvitation(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
// Cross-check the invitation lives in the URL :id. The route layer
// already verifies the caller has Owner on the active tenant AND
// the URL :id matches the active tenant (PathTenantMatch), but the
// invitation row itself carries its own tenant_id we have to honour
// — otherwise an Owner of A could revoke invitations of B by URL-
// crafting against /tenants/A/invitations/<inv-of-B>.
inv, err := h.invitationService.GetByID(ctx, invID)
if err != nil {
logger.Errorf(ctx, "GetByID invitation failed: id=%d err=%v", invID, err)
c.Error(apperrors.NewInternalServerError("failed to load invitation").WithDetails(err.Error()))
return
}
if inv == nil {
c.Error(apperrors.NewNotFoundError("invitation not found"))
return
}
if inv.TenantID != tenantID {
// Render the same 404 as "missing" so we don't leak existence
// across tenants.
c.Error(apperrors.NewNotFoundError("invitation not found"))
return
}
if err := h.invitationService.Revoke(ctx, invID); err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "RevokeInvitation failed: id=%d err=%v", invID, err)
c.Error(apperrors.NewInternalServerError("failed to revoke invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ListMyInvitations godoc
// @Summary 列出我的待接受邀请
// @Description 返回当前登录用户的待接受邀请(默认仅 pending),用于头像入口和 /invitations 收件箱页。
// @Tags 我的邀请
// @Produce json
// @Param include_terminal query bool false "是否包含已处理 / 已过期等终止态行(默认 false)"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations [get]
func (h *TenantInvitationHandler) ListMyInvitations(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
includeTerminal := strings.EqualFold(c.Query("include_terminal"), "true")
rows, err := h.invitationService.ListByInvitee(ctx, caller, includeTerminal)
if err != nil {
logger.Errorf(ctx, "ListByInvitee invitations failed: user=%s err=%v", caller, err)
c.Error(apperrors.NewInternalServerError("failed to list invitations").WithDetails(err.Error()))
return
}
usersByID := h.hydrateUsers(c, rows)
tenantsByID := h.hydrateTenants(c, rows)
resp := make([]types.TenantInvitationResponse, 0, len(rows))
for _, inv := range rows {
resp = append(resp, projectInvitation(inv, usersByID, tenantsByID))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"invitations": resp,
"total": len(resp),
},
})
}
// CountMyPendingInvitations godoc
// @Summary 获取我的待处理邀请数
// @Description 轻量级 endpoint,返回当前登录用户的 pending 邀请数,用于头像旁的角标轮询。
// @Tags 我的邀请
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/pending-count [get]
func (h *TenantInvitationHandler) CountMyPendingInvitations(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
count, err := h.invitationService.CountPendingByInvitee(ctx, caller)
if err != nil {
logger.Errorf(ctx, "CountPendingByInvitee failed: user=%s err=%v", caller, err)
c.Error(apperrors.NewInternalServerError("failed to count pending invitations").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{"pending_count": count},
})
}
// AcceptMyInvitation godoc
// @Summary 接受邀请
// @Description 当前登录用户接受一条 pending 邀请;服务端会同时写入 tenant_members 行。
// @Tags 我的邀请
// @Produce json
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/{inv_id}/accept [post]
func (h *TenantInvitationHandler) AcceptMyInvitation(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
member, err := h.invitationService.Accept(ctx, invID, caller)
if err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationForbidden):
c.Error(apperrors.NewForbiddenError(err.Error()))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrInvitationExpired):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "AcceptMyInvitation failed: id=%d user=%s err=%v",
invID, caller, err)
c.Error(apperrors.NewInternalServerError("failed to accept invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"membership": gin.H{
"tenant_id": member.TenantID,
"role": member.Role,
"status": member.Status,
"joined_at": member.JoinedAt,
},
},
})
}
// DeclineMyInvitation godoc
// @Summary 拒绝邀请
// @Description 当前登录用户拒绝一条 pending 邀请;不创建 tenant_members 行。
// @Tags 我的邀请
// @Produce json
// @Param inv_id path string true "邀请 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /me/invitations/{inv_id}/decline [post]
func (h *TenantInvitationHandler) DeclineMyInvitation(c *gin.Context) {
ctx := c.Request.Context()
caller, ok := types.UserIDFromContext(ctx)
if !ok || caller == "" {
c.Error(apperrors.NewUnauthorizedError("caller user id missing from context"))
return
}
invID, ok := parseInvitationIDFromPath(c)
if !ok {
return
}
if err := h.invitationService.Decline(ctx, invID, caller); err != nil {
switch {
case errors.Is(err, service.ErrInvitationNotFound):
c.Error(apperrors.NewNotFoundError("invitation not found"))
case errors.Is(err, service.ErrInvitationForbidden):
c.Error(apperrors.NewForbiddenError(err.Error()))
case errors.Is(err, service.ErrInvitationNotPending):
c.Error(apperrors.NewConflictError(err.Error()))
case errors.Is(err, service.ErrInvitationExpired):
c.Error(apperrors.NewConflictError(err.Error()))
default:
logger.Errorf(ctx, "DeclineMyInvitation failed: id=%d user=%s err=%v",
invID, caller, err)
c.Error(apperrors.NewInternalServerError("failed to decline invitation").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+33 -8
View File
@@ -86,10 +86,13 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
// ListMembers godoc
// @Summary 列出租户成员
// @Description 返回当前租户内全部 active 成员(含每位成员的角色、邮箱、头像)
// @Description 分页返回当前租户内 active 成员(含每位成员的角色、邮箱、头像);支持 q 按邮箱/用户名筛选
// @Tags 租户成员
// @Produce json
// @Param id path string true "租户 ID"
// @Param id path string true "租户 ID"
// @Param q query string false "按邮箱/用户名模糊筛选"
// @Param page query int false "页码(从 1 起)" default(1)
// @Param page_size query int false "每页数量(最大 100)" default(20)
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/members [get]
@@ -100,9 +103,15 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
return
}
members, err := h.memberService.ListByTenant(ctx, tenantID)
q := strings.TrimSpace(c.Query("q"))
page, pageSize, ok := parseListPagination(c)
if !ok {
return
}
members, total, err := h.memberService.ListMembersPage(ctx, tenantID, q, page, pageSize)
if err != nil {
logger.Errorf(ctx, "ListByTenant failed: tenant=%d err=%v", tenantID, err)
logger.Errorf(ctx, "ListMembersPage failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to list members").WithDetails(err.Error()))
return
}
@@ -144,15 +153,31 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"members": resp,
"total": len(resp),
"members": resp,
"total": total,
"page": page,
"page_size": pageSize,
},
})
}
// AddMember godoc
// @Summary 添加租户成员
// @Description Owner 通过 email 邀请已经存在的用户加入当前租户
// @Summary 直接添加租户成员(直加路径)
// @Description
//
// Owner 通过 email 直接把用户作为 active 成员添加进当前租户。
//
// 这是【直加路径】,被加入的用户没有任何确认机会就出现在租户里——
// 保留它是为了三类不需要走邀请确认的场景:
// 1. 自动化脚本 / 平台运维 / 数据迁移;
// 2. 跨租户超管 (CanAccessAllTenants) 的批量编排;
// 3. 对接外部 IdP 时由身份源单向同步成员。
//
// 所有由 UI 触发的「邀请伙伴加入」交互应改走
// POST /tenants/:id/invitations,那条路径会先创建 pending 行,让被邀请
// 人在 /me/invitations 主动接受后再写 tenant_members 行(PR #1303 后续)。
// 这条路径与 invitations 路径共存而不互相替代。
//
// @Tags 租户成员
// @Accept json
// @Produce json
+48 -4
View File
@@ -26,10 +26,46 @@ import (
// gotten here" assertions.
type stubMemberService struct {
interfaces.TenantMemberService
add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
remove func(ctx context.Context, userID string, tenantID uint64) error
add func(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
listTenant func(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
listMembersPage func(ctx context.Context, tenantID uint64, query string, page, pageSize int) ([]*types.TenantMember, int64, error)
updateRole func(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
remove func(ctx context.Context, userID string, tenantID uint64) error
}
func (s *stubMemberService) ListMembersPage(
ctx context.Context,
tenantID uint64,
query string,
page, pageSize int,
) ([]*types.TenantMember, int64, error) {
if s.listMembersPage != nil {
return s.listMembersPage(ctx, tenantID, query, page, pageSize)
}
if s.listTenant != nil {
members, err := s.listTenant(ctx, tenantID)
if err != nil {
return nil, 0, err
}
total := int64(len(members))
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 20
}
off := (page - 1) * pageSize
if off >= len(members) {
return []*types.TenantMember{}, total, nil
}
end := off + pageSize
if end > len(members) {
end = len(members)
}
slice := append([]*types.TenantMember(nil), members[off:end]...)
return slice, total, nil
}
return []*types.TenantMember{}, 0, nil
}
func (s *stubMemberService) AddMember(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error) {
@@ -260,6 +296,14 @@ func TestTenantMember_ListMembers_RejectsBadTenantID(t *testing.T) {
}
}
func TestTenantMember_ListMembers_RejectsInvalidPage(t *testing.T) {
h := newTestMemberHandler(&stubMemberService{}, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members?page=0", nil, "u1")
if w.Code != http.StatusBadRequest {
t.Fatalf("page=0 must 400, got %d body=%s", w.Code, w.Body.String())
}
}
// ---------- AddMember ----------
func TestTenantMember_AddMember_HappyPath(t *testing.T) {