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:
@@ -0,0 +1,257 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ErrPendingInvitationExists is returned by Create when a pending
|
||||
// invitation for (tenant_id, invitee_user_id) already exists. The
|
||||
// service layer maps it to its own sentinel for the handler.
|
||||
var ErrPendingInvitationExists = errors.New("repository: pending invitation already exists")
|
||||
|
||||
// tenantInvitationRepository implements interfaces.TenantInvitationRepository.
|
||||
type tenantInvitationRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewTenantInvitationRepository constructs the repo against db. Wired
|
||||
// up via the dig container alongside other repositories.
|
||||
func NewTenantInvitationRepository(db *gorm.DB) interfaces.TenantInvitationRepository {
|
||||
return &tenantInvitationRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new pending invitation row. The partial unique
|
||||
// index on (tenant_id, invitee_user_id) WHERE status='pending' is the
|
||||
// authoritative guard against duplicates, but we ALSO pre-check via
|
||||
// GetPendingByPair inside a tiny transaction so the typical "click
|
||||
// twice fast" case returns a clean sentinel instead of a raw 23505 /
|
||||
// SQLITE_CONSTRAINT error string the handler would have to parse.
|
||||
//
|
||||
// The pre-check is best-effort: two concurrent inserts can still race
|
||||
// past it, in which case the underlying database error surfaces. The
|
||||
// service layer treats any insert error containing the index name
|
||||
// (idx_tenant_invitations_unique_pending) as the conflict sentinel —
|
||||
// see invitationService.Create.
|
||||
func (r *tenantInvitationRepository) Create(
|
||||
ctx context.Context,
|
||||
inv *types.TenantInvitation,
|
||||
) error {
|
||||
if inv.Status == "" {
|
||||
inv.Status = types.TenantInvitationStatusPending
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var probe types.TenantInvitation
|
||||
err := tx.
|
||||
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
|
||||
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
|
||||
First(&probe).Error
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
// fallthrough — clean to insert.
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
return ErrPendingInvitationExists
|
||||
}
|
||||
return tx.Create(inv).Error
|
||||
})
|
||||
}
|
||||
|
||||
// GetByID returns the invitation row (regardless of status) or
|
||||
// (nil, nil) when missing. Used by Accept/Decline/Revoke flows that
|
||||
// must inspect status before transitioning.
|
||||
func (r *tenantInvitationRepository) GetByID(
|
||||
ctx context.Context,
|
||||
id uint64,
|
||||
) (*types.TenantInvitation, error) {
|
||||
var inv types.TenantInvitation
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&inv).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &inv, nil
|
||||
}
|
||||
|
||||
// GetPendingByPair returns the in-flight pending invitation, if any.
|
||||
func (r *tenantInvitationRepository) GetPendingByPair(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
inviteeUserID string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
var inv types.TenantInvitation
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
|
||||
tenantID, inviteeUserID, types.TenantInvitationStatusPending).
|
||||
First(&inv).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &inv, nil
|
||||
}
|
||||
|
||||
// listQuery centralises the "newest-first" ordering and includeTerminal
|
||||
// filter so ListByTenant / ListByInvitee stay short.
|
||||
func (r *tenantInvitationRepository) listQuery(includeTerminal bool) *gorm.DB {
|
||||
q := r.db.Order("id DESC")
|
||||
if !includeTerminal {
|
||||
q = q.Where("status = ?", types.TenantInvitationStatusPending)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// tenantInvitationTenantScope applies tenant_id, optional pending-only
|
||||
// filter, and id DESC ordering — shared by ListByTenant and paging helpers.
|
||||
func (r *tenantInvitationRepository) tenantInvitationTenantScope(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
) *gorm.DB {
|
||||
q := r.db.WithContext(ctx).
|
||||
Model(&types.TenantInvitation{}).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("id DESC")
|
||||
if !includeTerminal {
|
||||
q = q.Where("status = ?", types.TenantInvitationStatusPending)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// ListByTenant returns invitations for the tenant ordered by id DESC.
|
||||
func (r *tenantInvitationRepository) ListByTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
var rows []*types.TenantInvitation
|
||||
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// CountByTenantList counts invitations matching ListByTenant filters.
|
||||
func (r *tenantInvitationRepository) CountByTenantList(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
) (int64, error) {
|
||||
var n int64
|
||||
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
|
||||
Count(&n).Error
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ListByTenantPage returns a page of invitations (id DESC).
|
||||
func (r *tenantInvitationRepository) ListByTenantPage(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
offset, limit int,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
var rows []*types.TenantInvitation
|
||||
err := r.tenantInvitationTenantScope(ctx, tenantID, includeTerminal).
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ListByInvitee returns invitations addressed to the user across all
|
||||
// tenants.
|
||||
func (r *tenantInvitationRepository) ListByInvitee(
|
||||
ctx context.Context,
|
||||
inviteeUserID string,
|
||||
includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
var rows []*types.TenantInvitation
|
||||
err := r.listQuery(includeTerminal).
|
||||
WithContext(ctx).
|
||||
Where("invitee_user_id = ?", inviteeUserID).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// CountPendingByInvitee returns the pending invitation count for the user.
|
||||
func (r *tenantInvitationRepository) CountPendingByInvitee(
|
||||
ctx context.Context,
|
||||
inviteeUserID string,
|
||||
) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&types.TenantInvitation{}).
|
||||
Where("invitee_user_id = ? AND status = ?",
|
||||
inviteeUserID, types.TenantInvitationStatusPending).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// MarkStatusIfPending atomically transitions a row from pending to
|
||||
// the supplied terminal status. The WHERE filter on status='pending'
|
||||
// is what makes this safe under concurrent accept/revoke clicks —
|
||||
// only the first writer succeeds; the second sees RowsAffected=0 and
|
||||
// receives gorm.ErrRecordNotFound (which the service maps to a
|
||||
// "already finalised" sentinel).
|
||||
func (r *tenantInvitationRepository) MarkStatusIfPending(
|
||||
ctx context.Context,
|
||||
id uint64,
|
||||
status types.TenantInvitationStatus,
|
||||
respondedAt time.Time,
|
||||
) error {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&types.TenantInvitation{}).
|
||||
Where("id = ? AND status = ?", id, types.TenantInvitationStatusPending).
|
||||
Updates(map[string]any{
|
||||
"status": status,
|
||||
"responded_at": respondedAt,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SweepExpired transitions all overdue pending rows to expired in a
|
||||
// single batch. We intentionally don't emit per-row audit events from
|
||||
// here — the original rbac.invitation_sent already lives in the audit
|
||||
// log, and a sweep can touch many rows on a sleepy weekend (an audit
|
||||
// fanout would dwarf the original event volume).
|
||||
func (r *tenantInvitationRepository) SweepExpired(
|
||||
ctx context.Context,
|
||||
now time.Time,
|
||||
) (int64, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&types.TenantInvitation{}).
|
||||
Where("status = ? AND expires_at < ?", types.TenantInvitationStatusPending, now).
|
||||
Updates(map[string]any{
|
||||
"status": types.TenantInvitationStatusExpired,
|
||||
"responded_at": now,
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -92,6 +93,56 @@ func (r *tenantMemberRepository) ListByTenant(ctx context.Context, tenantID uint
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// CountFilteredByTenant counts active tenant membership rows, optionally
|
||||
// restricted to users whose email or username matches search.
|
||||
func (r *tenantMemberRepository) CountFilteredByTenant(
|
||||
ctx context.Context, tenantID uint64, search string,
|
||||
) (int64, error) {
|
||||
search = strings.TrimSpace(search)
|
||||
q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
|
||||
Where("tenant_id = ?", tenantID)
|
||||
var total int64
|
||||
var err error
|
||||
if search == "" {
|
||||
err = q.Count(&total).Error
|
||||
} else {
|
||||
like := "%" + escapeLikePattern(search) + "%"
|
||||
err = q.
|
||||
Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
|
||||
Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
|
||||
Count(&total).Error
|
||||
}
|
||||
return total, err
|
||||
}
|
||||
|
||||
// ListPagedByTenant lists active memberships with stable sort.
|
||||
func (r *tenantMemberRepository) ListPagedByTenant(
|
||||
ctx context.Context, tenantID uint64, search string, offset, limit int,
|
||||
) ([]*types.TenantMember, error) {
|
||||
search = strings.TrimSpace(search)
|
||||
var members []*types.TenantMember
|
||||
q := r.db.WithContext(ctx).Model(&types.TenantMember{}).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("tenant_members.joined_at ASC, tenant_members.id ASC").
|
||||
Offset(offset).
|
||||
Limit(limit)
|
||||
|
||||
var err error
|
||||
if search == "" {
|
||||
err = q.Find(&members).Error
|
||||
} else {
|
||||
like := "%" + escapeLikePattern(search) + "%"
|
||||
err = q.
|
||||
Joins(`INNER JOIN users ON users.id = tenant_members.user_id AND users.deleted_at IS NULL`).
|
||||
Where(`(LOWER(users.email) LIKE LOWER(?) OR LOWER(users.username) LIKE LOWER(?))`, like, like).
|
||||
Find(&members).Error
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// UpdateRole changes the role of an existing active membership.
|
||||
func (r *tenantMemberRepository) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
|
||||
res := r.db.WithContext(ctx).
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Sentinel errors returned by tenantInvitationService. Callers compare
|
||||
// with errors.Is to render the appropriate HTTP responses.
|
||||
var (
|
||||
// ErrInvitationNotFound is returned when no invitation row matches
|
||||
// the supplied id.
|
||||
ErrInvitationNotFound = errors.New("invitation not found")
|
||||
|
||||
// ErrPendingInvitationExists is returned by Create when a pending
|
||||
// invitation for (tenant, invitee) is already in flight. The
|
||||
// handler maps this to 409.
|
||||
ErrPendingInvitationExists = errors.New("a pending invitation for this user already exists")
|
||||
|
||||
// ErrAlreadyMember is returned by Create when the invitee is
|
||||
// already an active member of the tenant; sending an invite would
|
||||
// be a no-op at best and a confusing UX at worst.
|
||||
ErrAlreadyMember = errors.New("user is already an active member of the tenant")
|
||||
|
||||
// ErrInvitationNotPending is returned by Accept / Decline / Revoke
|
||||
// when the row exists but has already been finalised. Maps to 409.
|
||||
ErrInvitationNotPending = errors.New("invitation is no longer pending")
|
||||
|
||||
// ErrInvitationExpired is returned by Accept / Decline when the
|
||||
// pending row has aged past its expires_at. Maps to 410.
|
||||
ErrInvitationExpired = errors.New("invitation has expired")
|
||||
|
||||
// ErrInvitationForbidden is returned by Accept / Decline when the
|
||||
// caller is not the invitee. Owner-driven Revoke is gated at the
|
||||
// route layer so this error only surfaces on the /me/ paths.
|
||||
ErrInvitationForbidden = errors.New("only the invitee can accept or decline this invitation")
|
||||
)
|
||||
|
||||
// defaultInvitationTTL is the lifetime of a pending invitation before
|
||||
// the lazy sweep transitions it to expired. Operator override is via
|
||||
// the WEKNORA_INVITATION_TTL env var (Go duration: "168h", "7d-ish");
|
||||
// keeping this out of TenantConfig avoids a yaml migration for a knob
|
||||
// that almost nobody is going to tweak.
|
||||
const defaultInvitationTTL = 7 * 24 * time.Hour
|
||||
|
||||
// invitationTTL resolves the effective TTL at call time so an operator
|
||||
// can hot-reload the override without restarting. The env var is parsed
|
||||
// once per call; cost is negligible and beats a goroutine watching the
|
||||
// environment.
|
||||
func invitationTTL() time.Duration {
|
||||
raw := os.Getenv("WEKNORA_INVITATION_TTL")
|
||||
if raw == "" {
|
||||
return defaultInvitationTTL
|
||||
}
|
||||
if d, err := time.ParseDuration(raw); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
// Allow "604800" seconds for callers that don't like Go duration
|
||||
// syntax — same shape as the rest of our int env knobs.
|
||||
if secs, err := strconv.ParseInt(raw, 10, 64); err == nil && secs > 0 {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
return defaultInvitationTTL
|
||||
}
|
||||
|
||||
// tenantInvitationService implements interfaces.TenantInvitationService.
|
||||
type tenantInvitationService struct {
|
||||
repo interfaces.TenantInvitationRepository
|
||||
memberSvc interfaces.TenantMemberService
|
||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||
now func() time.Time // injection seam for tests
|
||||
}
|
||||
|
||||
// NewTenantInvitationService wires the dependencies. memberSvc is
|
||||
// required (Accept must create the tenant_members row); audit is
|
||||
// optional and matches the same nil-safe pattern tenantMemberService
|
||||
// uses.
|
||||
func NewTenantInvitationService(
|
||||
repo interfaces.TenantInvitationRepository,
|
||||
memberSvc interfaces.TenantMemberService,
|
||||
audit interfaces.AuditLogService,
|
||||
) interfaces.TenantInvitationService {
|
||||
return &tenantInvitationService{
|
||||
repo: repo,
|
||||
memberSvc: memberSvc,
|
||||
audit: audit,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// emitAudit is the best-effort audit hook; mirrors tenantMemberService.
|
||||
func (s *tenantInvitationService) emitAudit(ctx context.Context, entry *types.AuditLog) {
|
||||
if s.audit == nil {
|
||||
return
|
||||
}
|
||||
_ = s.audit.Log(ctx, entry)
|
||||
}
|
||||
|
||||
// detailsFor packs the role + invitation id into the audit Details so a
|
||||
// reader can reconstruct "Alice invited Bob as Admin (inv #42)" without
|
||||
// joining back to the invitations table.
|
||||
func detailsFor(invID uint64, role types.TenantRole) types.JSON {
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"invitation_id": invID,
|
||||
"role": string(role),
|
||||
})
|
||||
return types.JSON(b)
|
||||
}
|
||||
|
||||
// sweep transitions overdue pending rows to expired before any List/
|
||||
// Accept/Decline/Count read. Failures are logged and swallowed — a
|
||||
// transient sweep error must not block a user from reading their
|
||||
// inbox; the next call will sweep again.
|
||||
func (s *tenantInvitationService) sweep(ctx context.Context) {
|
||||
if _, err := s.repo.SweepExpired(ctx, s.now()); err != nil {
|
||||
logger.Warnf(ctx, "tenant_invitation lazy sweep failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create issues a new pending invitation. Returns the standard
|
||||
// conflict sentinels for the duplicate-pending and already-member
|
||||
// cases.
|
||||
func (s *tenantInvitationService) Create(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
inviteeUserID string,
|
||||
role types.TenantRole,
|
||||
invitedBy *string,
|
||||
message string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
if !role.IsValid() {
|
||||
return nil, ErrInvalidTenantRole
|
||||
}
|
||||
// Reject early if the invitee is already an active member; the
|
||||
// handler renders this as "they're already in" rather than the
|
||||
// generic conflict.
|
||||
existing, err := s.memberSvc.GetMembership(ctx, inviteeUserID, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil && existing.Status == types.TenantMemberStatusActive {
|
||||
return nil, ErrAlreadyMember
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
inv := &types.TenantInvitation{
|
||||
TenantID: tenantID,
|
||||
InviteeUserID: inviteeUserID,
|
||||
InvitedBy: invitedBy,
|
||||
Role: role,
|
||||
Status: types.TenantInvitationStatusPending,
|
||||
Message: message,
|
||||
ExpiresAt: now.Add(invitationTTL()),
|
||||
}
|
||||
if err := s.repo.Create(ctx, inv); err != nil {
|
||||
if errors.Is(err, apprepo.ErrPendingInvitationExists) {
|
||||
return nil, ErrPendingInvitationExists
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: tenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationSent,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
TargetUserID: inviteeUserID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, role),
|
||||
})
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
// Accept transitions a pending invitation into accepted AND creates
|
||||
// the active tenant_members row in the same flow. We do NOT wrap both
|
||||
// writes in a single DB transaction because TenantMemberService.AddMember
|
||||
// owns its own write + audit emit and reaching across services here
|
||||
// would force the audit-log writes to commit/rollback in lockstep.
|
||||
// Instead, we order operations so the user-visible failure mode is
|
||||
// "you couldn't accept the invitation"; if the membership insert fails
|
||||
// AFTER the invitation transition committed (rare; collision on the
|
||||
// tenant_members unique index would be the only realistic case), the
|
||||
// row already in tenant_members wins and a subsequent Accept call sees
|
||||
// ErrInvitationNotPending which the handler renders as 409.
|
||||
func (s *tenantInvitationService) Accept(
|
||||
ctx context.Context,
|
||||
invID uint64,
|
||||
callerUserID string,
|
||||
) (*types.TenantMember, error) {
|
||||
s.sweep(ctx)
|
||||
|
||||
inv, err := s.repo.GetByID(ctx, invID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if inv == nil {
|
||||
return nil, ErrInvitationNotFound
|
||||
}
|
||||
if inv.InviteeUserID != callerUserID {
|
||||
return nil, ErrInvitationForbidden
|
||||
}
|
||||
if inv.Status != types.TenantInvitationStatusPending {
|
||||
return nil, ErrInvitationNotPending
|
||||
}
|
||||
if inv.IsExpired(s.now()) {
|
||||
// The sweep above should have flipped it already, but a row
|
||||
// can age past expires_at between the sweep and this read.
|
||||
// Treat it as expired regardless.
|
||||
return nil, ErrInvitationExpired
|
||||
}
|
||||
|
||||
now := s.now()
|
||||
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusAccepted, now); err != nil {
|
||||
// Another goroutine (concurrent click) won the race. Honour
|
||||
// the state machine.
|
||||
return nil, ErrInvitationNotPending
|
||||
}
|
||||
|
||||
// Create the actual tenant_members row. Cross-service hop: the
|
||||
// member service handles its own audit (rbac.member_added) and
|
||||
// also enforces the (user, tenant) uniqueness invariant via the
|
||||
// repo. If it fails here the invitation is already accepted —
|
||||
// see comment above for why we don't rollback the invitation.
|
||||
member, err := s.memberSvc.AddMember(ctx, inv.InviteeUserID, inv.TenantID, inv.Role, inv.InvitedBy)
|
||||
if err != nil {
|
||||
// Special-case "already a member": that's the idempotent
|
||||
// outcome we want. Return the existing membership instead of
|
||||
// bubbling the error up to the invitee.
|
||||
if errors.Is(err, ErrMembershipAlreadyExists) {
|
||||
existing, getErr := s.memberSvc.GetMembership(ctx, inv.InviteeUserID, inv.TenantID)
|
||||
if getErr == nil && existing != nil {
|
||||
s.emitInvitationAccepted(ctx, inv)
|
||||
return existing, nil
|
||||
}
|
||||
}
|
||||
logger.Errorf(ctx,
|
||||
"invitation %d accepted but tenant_members insert failed: %v",
|
||||
invID, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.emitInvitationAccepted(ctx, inv)
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// emitInvitationAccepted writes the rbac.invitation_accepted audit row.
|
||||
// Actor is the invitee (acting on their own inbox); target is the same
|
||||
// user since the action is self-directed.
|
||||
func (s *tenantInvitationService) emitInvitationAccepted(ctx context.Context, inv *types.TenantInvitation) {
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: inv.TenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationAccepted,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
TargetUserID: inv.InviteeUserID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, inv.Role),
|
||||
})
|
||||
}
|
||||
|
||||
// Decline transitions the pending row into declined. Only the invitee
|
||||
// themselves can call this.
|
||||
func (s *tenantInvitationService) Decline(
|
||||
ctx context.Context,
|
||||
invID uint64,
|
||||
callerUserID string,
|
||||
) error {
|
||||
s.sweep(ctx)
|
||||
|
||||
inv, err := s.repo.GetByID(ctx, invID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if inv == nil {
|
||||
return ErrInvitationNotFound
|
||||
}
|
||||
if inv.InviteeUserID != callerUserID {
|
||||
return ErrInvitationForbidden
|
||||
}
|
||||
if inv.Status != types.TenantInvitationStatusPending {
|
||||
return ErrInvitationNotPending
|
||||
}
|
||||
if inv.IsExpired(s.now()) {
|
||||
return ErrInvitationExpired
|
||||
}
|
||||
|
||||
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusDeclined, s.now()); err != nil {
|
||||
return ErrInvitationNotPending
|
||||
}
|
||||
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: inv.TenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationDeclined,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
TargetUserID: inv.InviteeUserID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, inv.Role),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Revoke transitions the pending row into revoked. Route-layer Owner
|
||||
// gate guarantees the caller is allowed to act on this tenant; this
|
||||
// method does not re-check role.
|
||||
func (s *tenantInvitationService) Revoke(ctx context.Context, invID uint64) error {
|
||||
s.sweep(ctx)
|
||||
|
||||
inv, err := s.repo.GetByID(ctx, invID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if inv == nil {
|
||||
return ErrInvitationNotFound
|
||||
}
|
||||
if inv.Status != types.TenantInvitationStatusPending {
|
||||
return ErrInvitationNotPending
|
||||
}
|
||||
|
||||
if err := s.repo.MarkStatusIfPending(ctx, invID, types.TenantInvitationStatusRevoked, s.now()); err != nil {
|
||||
return ErrInvitationNotPending
|
||||
}
|
||||
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: inv.TenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationRevoked,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
TargetUserID: inv.InviteeUserID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, inv.Role),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID returns the row or (nil, nil) without sweeping. The handler
|
||||
// uses this for narrow per-row checks where running a full sweep just
|
||||
// to read one row would be wasted work; List* paths still sweep.
|
||||
func (s *tenantInvitationService) GetByID(
|
||||
ctx context.Context,
|
||||
invID uint64,
|
||||
) (*types.TenantInvitation, error) {
|
||||
return s.repo.GetByID(ctx, invID)
|
||||
}
|
||||
|
||||
// ListByTenant sweeps then returns. The tenant-side management UI
|
||||
// expects expired rows to surface correctly; running the sweep here
|
||||
// guarantees the page reflects reality even if no other code path has
|
||||
// touched the table recently.
|
||||
func (s *tenantInvitationService) ListByTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
s.sweep(ctx)
|
||||
return s.repo.ListByTenant(ctx, tenantID, includeTerminal)
|
||||
}
|
||||
|
||||
// ListTenantInvitationsPage sweeps then returns a page plus total rows
|
||||
// matching the same filter as ListByTenant.
|
||||
func (s *tenantInvitationService) ListTenantInvitationsPage(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
page, pageSize int,
|
||||
) ([]*types.TenantInvitation, int64, error) {
|
||||
const (
|
||||
defSize = 20
|
||||
maxSize = 100
|
||||
)
|
||||
s.sweep(ctx)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = defSize
|
||||
}
|
||||
if pageSize > maxSize {
|
||||
pageSize = maxSize
|
||||
}
|
||||
total, err := s.repo.CountByTenantList(ctx, tenantID, includeTerminal)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
rows, err := s.repo.ListByTenantPage(ctx, tenantID, includeTerminal, offset, pageSize)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return rows, total, nil
|
||||
}
|
||||
|
||||
// ListByInvitee sweeps then returns. Same reasoning as ListByTenant.
|
||||
func (s *tenantInvitationService) ListByInvitee(
|
||||
ctx context.Context,
|
||||
inviteeUserID string,
|
||||
includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
s.sweep(ctx)
|
||||
return s.repo.ListByInvitee(ctx, inviteeUserID, includeTerminal)
|
||||
}
|
||||
|
||||
// CountPendingByInvitee sweeps then counts. The avatar-row badge polls
|
||||
// this endpoint so a stale sweep would manifest as a phantom "1" on
|
||||
// the bell icon for the full polling interval; sweeping inline is
|
||||
// worth the extra UPDATE.
|
||||
func (s *tenantInvitationService) CountPendingByInvitee(
|
||||
ctx context.Context,
|
||||
inviteeUserID string,
|
||||
) (int64, error) {
|
||||
s.sweep(ctx)
|
||||
return s.repo.CountPendingByInvitee(ctx, inviteeUserID)
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// fakeInvitationRepo is an in-memory stand-in for
|
||||
// interfaces.TenantInvitationRepository. The implementation is
|
||||
// deliberately tiny — these tests focus on the service-layer state
|
||||
// machine (Accept / Decline / Revoke / lazy sweep / duplicate guard)
|
||||
// rather than the SQL surface. The production repo gets exercised via
|
||||
// the real DB in repo tests if/when those are added.
|
||||
type fakeInvitationRepo struct {
|
||||
rows []*types.TenantInvitation
|
||||
nextID uint64
|
||||
}
|
||||
|
||||
func newFakeInvitationRepo() *fakeInvitationRepo { return &fakeInvitationRepo{} }
|
||||
|
||||
func (r *fakeInvitationRepo) Create(ctx context.Context, inv *types.TenantInvitation) error {
|
||||
for _, e := range r.rows {
|
||||
if e.TenantID == inv.TenantID &&
|
||||
e.InviteeUserID == inv.InviteeUserID &&
|
||||
e.Status == types.TenantInvitationStatusPending {
|
||||
return apprepo.ErrPendingInvitationExists
|
||||
}
|
||||
}
|
||||
r.nextID++
|
||||
inv.ID = r.nextID
|
||||
inv.CreatedAt = time.Now()
|
||||
inv.UpdatedAt = inv.CreatedAt
|
||||
cp := *inv
|
||||
r.rows = append(r.rows, &cp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) GetByID(ctx context.Context, id uint64) (*types.TenantInvitation, error) {
|
||||
for _, e := range r.rows {
|
||||
if e.ID == id {
|
||||
cp := *e
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) GetPendingByPair(
|
||||
ctx context.Context, tenantID uint64, inviteeUserID string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
for _, e := range r.rows {
|
||||
if e.TenantID == tenantID &&
|
||||
e.InviteeUserID == inviteeUserID &&
|
||||
e.Status == types.TenantInvitationStatusPending {
|
||||
cp := *e
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) filteredTenantRows(
|
||||
tenantID uint64, includeTerminal bool,
|
||||
) []*types.TenantInvitation {
|
||||
var out []*types.TenantInvitation
|
||||
for _, e := range r.rows {
|
||||
if e.TenantID != tenantID {
|
||||
continue
|
||||
}
|
||||
if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
|
||||
continue
|
||||
}
|
||||
cp := *e
|
||||
out = append(out, &cp)
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
return out[i].ID > out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) ListByTenant(
|
||||
ctx context.Context, tenantID uint64, includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
return r.filteredTenantRows(tenantID, includeTerminal), nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) CountByTenantList(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
) (int64, error) {
|
||||
return int64(len(r.filteredTenantRows(tenantID, includeTerminal))), nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) ListByTenantPage(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
includeTerminal bool,
|
||||
offset, limit int,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
all := r.filteredTenantRows(tenantID, includeTerminal)
|
||||
if offset >= len(all) {
|
||||
return []*types.TenantInvitation{}, nil
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
return append([]*types.TenantInvitation(nil), all[offset:end]...), nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) ListByInvitee(
|
||||
ctx context.Context, inviteeUserID string, includeTerminal bool,
|
||||
) ([]*types.TenantInvitation, error) {
|
||||
var out []*types.TenantInvitation
|
||||
for _, e := range r.rows {
|
||||
if e.InviteeUserID != inviteeUserID {
|
||||
continue
|
||||
}
|
||||
if !includeTerminal && e.Status != types.TenantInvitationStatusPending {
|
||||
continue
|
||||
}
|
||||
cp := *e
|
||||
out = append(out, &cp)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) CountPendingByInvitee(
|
||||
ctx context.Context, inviteeUserID string,
|
||||
) (int64, error) {
|
||||
var n int64
|
||||
for _, e := range r.rows {
|
||||
if e.InviteeUserID == inviteeUserID &&
|
||||
e.Status == types.TenantInvitationStatusPending {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) MarkStatusIfPending(
|
||||
ctx context.Context,
|
||||
id uint64,
|
||||
status types.TenantInvitationStatus,
|
||||
respondedAt time.Time,
|
||||
) error {
|
||||
for _, e := range r.rows {
|
||||
if e.ID == id && e.Status == types.TenantInvitationStatusPending {
|
||||
e.Status = status
|
||||
e.RespondedAt = &respondedAt
|
||||
e.UpdatedAt = time.Now()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return gormErrRecordNotFound
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) SweepExpired(
|
||||
ctx context.Context, now time.Time,
|
||||
) (int64, error) {
|
||||
var n int64
|
||||
for _, e := range r.rows {
|
||||
if e.Status == types.TenantInvitationStatusPending && e.ExpiresAt.Before(now) {
|
||||
e.Status = types.TenantInvitationStatusExpired
|
||||
e.RespondedAt = &now
|
||||
e.UpdatedAt = time.Now()
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
var _ interfaces.TenantInvitationRepository = (*fakeInvitationRepo)(nil)
|
||||
|
||||
// newInvitationSvc returns a service wired against in-memory fakes for
|
||||
// both the invitation repo and the member service. Audit is nil so
|
||||
// the lazy emitAudit short-circuit keeps the test surface focused.
|
||||
func newInvitationSvc() (
|
||||
interfaces.TenantInvitationService,
|
||||
*fakeInvitationRepo,
|
||||
interfaces.TenantMemberService,
|
||||
) {
|
||||
invRepo := newFakeInvitationRepo()
|
||||
memberSvc, _ := newServiceWithRepo()
|
||||
svc := NewTenantInvitationService(invRepo, memberSvc, nil)
|
||||
return svc, invRepo, memberSvc
|
||||
}
|
||||
|
||||
func TestInvitationService_Create_RejectsInvalidRole(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
_, err := svc.Create(context.Background(), 1, "u-bob", types.TenantRole("magician"), nil, "")
|
||||
if !errors.Is(err, ErrInvalidTenantRole) {
|
||||
t.Fatalf("want ErrInvalidTenantRole, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Create_RejectsAlreadyActiveMember(t *testing.T) {
|
||||
svc, _, memberSvc := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleContributor, nil); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
_, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
|
||||
if !errors.Is(err, ErrAlreadyMember) {
|
||||
t.Fatalf("want ErrAlreadyMember, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Create_DedupsPending(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
|
||||
t.Fatalf("first invite: %v", err)
|
||||
}
|
||||
_, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
|
||||
if !errors.Is(err, ErrPendingInvitationExists) {
|
||||
t.Fatalf("want ErrPendingInvitationExists, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Accept_OnlyByInvitee(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if _, err := svc.Accept(ctx, inv.ID, "u-eve"); !errors.Is(err, ErrInvitationForbidden) {
|
||||
t.Fatalf("non-invitee must be forbidden, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Accept_HappyPath_CreatesMembership(t *testing.T) {
|
||||
svc, _, memberSvc := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
mb, err := svc.Accept(ctx, inv.ID, "u-bob")
|
||||
if err != nil {
|
||||
t.Fatalf("accept: %v", err)
|
||||
}
|
||||
if mb == nil || mb.UserID != "u-bob" || mb.Role != types.TenantRoleAdmin {
|
||||
t.Fatalf("unexpected membership: %+v", mb)
|
||||
}
|
||||
// Re-acceptance must be a state-machine rejection, not silent
|
||||
// success — otherwise a duplicate click double-creates audit rows.
|
||||
if _, err := svc.Accept(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
|
||||
t.Fatalf("re-accept must reject as ErrInvitationNotPending, got %v", err)
|
||||
}
|
||||
// And the membership service must see the row exactly once.
|
||||
got, _ := memberSvc.GetMembership(ctx, "u-bob", 1)
|
||||
if got == nil {
|
||||
t.Fatalf("membership row missing after accept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Accept_IdempotentWhenAlreadyMember(t *testing.T) {
|
||||
// If the invitee somehow became an active member between Create
|
||||
// and Accept (e.g. a parallel direct-add via POST /members), the
|
||||
// Accept call must not 500 — it should fold gracefully into "you
|
||||
// are already in" and flip the invitation to accepted for audit.
|
||||
svc, invRepo, memberSvc := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
// Side-effect: mint the membership directly.
|
||||
if _, err := memberSvc.AddMember(ctx, "u-bob", 1, types.TenantRoleViewer, nil); err != nil {
|
||||
t.Fatalf("side-effect AddMember: %v", err)
|
||||
}
|
||||
mb, err := svc.Accept(ctx, inv.ID, "u-bob")
|
||||
if err != nil {
|
||||
t.Fatalf("accept must be idempotent, got %v", err)
|
||||
}
|
||||
if mb == nil || mb.Role != types.TenantRoleViewer {
|
||||
// Returns the pre-existing membership; the role on the
|
||||
// invitation does NOT clobber a real membership row.
|
||||
t.Fatalf("unexpected membership after idempotent accept: %+v", mb)
|
||||
}
|
||||
// Invitation row must reflect accepted state so the inbox no
|
||||
// longer surfaces it as pending.
|
||||
row, _ := invRepo.GetByID(ctx, inv.ID)
|
||||
if row == nil || row.Status != types.TenantInvitationStatusAccepted {
|
||||
t.Fatalf("invitation must be accepted after idempotent accept, got %+v", row)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Decline_MarksDeclined(t *testing.T) {
|
||||
svc, invRepo, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if err := svc.Decline(ctx, inv.ID, "u-bob"); err != nil {
|
||||
t.Fatalf("decline: %v", err)
|
||||
}
|
||||
row, _ := invRepo.GetByID(ctx, inv.ID)
|
||||
if row.Status != types.TenantInvitationStatusDeclined {
|
||||
t.Fatalf("want declined status, got %s", row.Status)
|
||||
}
|
||||
if err := svc.Decline(ctx, inv.ID, "u-bob"); !errors.Is(err, ErrInvitationNotPending) {
|
||||
t.Fatalf("double-decline must reject, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_Revoke_MarksRevoked(t *testing.T) {
|
||||
svc, invRepo, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleAdmin, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if err := svc.Revoke(ctx, inv.ID); err != nil {
|
||||
t.Fatalf("revoke: %v", err)
|
||||
}
|
||||
row, _ := invRepo.GetByID(ctx, inv.ID)
|
||||
if row.Status != types.TenantInvitationStatusRevoked {
|
||||
t.Fatalf("want revoked status, got %s", row.Status)
|
||||
}
|
||||
// Revoked rows can be re-invited via a fresh Create — the
|
||||
// partial unique index only guards PENDING.
|
||||
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleContributor, nil, ""); err != nil {
|
||||
t.Fatalf("re-invite after revoke must succeed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_LazySweepExpires(t *testing.T) {
|
||||
// Drop a row directly into the repo with an ExpiresAt in the past,
|
||||
// then call ListByInvitee — the sweep must flip it to expired
|
||||
// before the read returns.
|
||||
svc, invRepo, _ := newInvitationSvc()
|
||||
now := time.Now()
|
||||
stale := &types.TenantInvitation{
|
||||
TenantID: 1,
|
||||
InviteeUserID: "u-bob",
|
||||
Role: types.TenantRoleViewer,
|
||||
Status: types.TenantInvitationStatusPending,
|
||||
ExpiresAt: now.Add(-time.Hour),
|
||||
}
|
||||
if err := invRepo.Create(context.Background(), stale); err != nil {
|
||||
t.Fatalf("seed stale: %v", err)
|
||||
}
|
||||
|
||||
rows, err := svc.ListByInvitee(context.Background(), "u-bob", true)
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].Status != types.TenantInvitationStatusExpired {
|
||||
t.Fatalf("expected expired row after sweep, got %+v", rows)
|
||||
}
|
||||
|
||||
// And accepting an expired invitation must fail loudly rather than
|
||||
// quietly creating the membership.
|
||||
if _, err := svc.Accept(context.Background(), stale.ID, "u-bob"); err == nil {
|
||||
t.Fatalf("accept on expired invitation must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_CountPending(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
if _, err := svc.Create(ctx, 1, "u-bob", types.TenantRoleViewer, nil, ""); err != nil {
|
||||
t.Fatalf("seed1: %v", err)
|
||||
}
|
||||
if _, err := svc.Create(ctx, 2, "u-bob", types.TenantRoleAdmin, nil, ""); err != nil {
|
||||
t.Fatalf("seed2: %v", err)
|
||||
}
|
||||
n, err := svc.CountPendingByInvitee(ctx, "u-bob")
|
||||
if err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if n != 2 {
|
||||
t.Fatalf("want 2 pending, got %d", n)
|
||||
}
|
||||
// Decline one; count drops.
|
||||
rows, _ := svc.ListByInvitee(ctx, "u-bob", false)
|
||||
if err := svc.Decline(ctx, rows[0].ID, "u-bob"); err != nil {
|
||||
t.Fatalf("decline: %v", err)
|
||||
}
|
||||
n, _ = svc.CountPendingByInvitee(ctx, "u-bob")
|
||||
if n != 1 {
|
||||
t.Fatalf("want 1 pending after decline, got %d", n)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
@@ -33,6 +34,11 @@ var (
|
||||
ErrLastOwner = errors.New("cannot demote or remove the last active owner of the tenant")
|
||||
)
|
||||
|
||||
const (
|
||||
listMembersDefaultPageSize = 20
|
||||
listMembersMaxPageSize = 100
|
||||
)
|
||||
|
||||
// tenantMemberService implements interfaces.TenantMemberService.
|
||||
type tenantMemberService struct {
|
||||
repo interfaces.TenantMemberRepository
|
||||
@@ -172,6 +178,36 @@ func (s *tenantMemberService) ListByTenant(ctx context.Context, tenantID uint64)
|
||||
return s.repo.ListByTenant(ctx, tenantID)
|
||||
}
|
||||
|
||||
// ListMembersPage returns a slice plus total matching query (handlers parse
|
||||
// page/page_size; defensive clamps here mirror list handler limits).
|
||||
func (s *tenantMemberService) ListMembersPage(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
query string,
|
||||
page, pageSize int,
|
||||
) ([]*types.TenantMember, int64, error) {
|
||||
query = strings.TrimSpace(query)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = listMembersDefaultPageSize
|
||||
}
|
||||
if pageSize > listMembersMaxPageSize {
|
||||
pageSize = listMembersMaxPageSize
|
||||
}
|
||||
total, err := s.repo.CountFilteredByTenant(ctx, tenantID, query)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
members, err := s.repo.ListPagedByTenant(ctx, tenantID, query, offset, pageSize)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return members, total, nil
|
||||
}
|
||||
|
||||
// HasAnyMembers proxies to the repository.
|
||||
func (s *tenantMemberService) HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error) {
|
||||
return s.repo.HasAnyMembers(ctx, tenantID)
|
||||
|
||||
@@ -3,6 +3,8 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -90,6 +92,50 @@ func (r *fakeTenantMemberRepo) ListByTenant(ctx context.Context, tenantID uint64
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantMemberRepo) filterTenantRows(tenantID uint64, search string) []*types.TenantMember {
|
||||
search = strings.TrimSpace(strings.ToLower(search))
|
||||
var out []*types.TenantMember
|
||||
for _, e := range r.rows {
|
||||
if e.TenantID != tenantID || e.DeletedAt.Valid {
|
||||
continue
|
||||
}
|
||||
if search != "" {
|
||||
if !strings.Contains(strings.ToLower(e.UserID), search) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
cp := *e
|
||||
out = append(out, &cp)
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if out[i].JoinedAt.Equal(out[j].JoinedAt) {
|
||||
return out[i].ID < out[j].ID
|
||||
}
|
||||
return out[i].JoinedAt.Before(out[j].JoinedAt)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *fakeTenantMemberRepo) CountFilteredByTenant(
|
||||
ctx context.Context, tenantID uint64, search string,
|
||||
) (int64, error) {
|
||||
return int64(len(r.filterTenantRows(tenantID, search))), nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantMemberRepo) ListPagedByTenant(
|
||||
ctx context.Context, tenantID uint64, search string, offset, limit int,
|
||||
) ([]*types.TenantMember, error) {
|
||||
all := r.filterTenantRows(tenantID, search)
|
||||
if offset >= len(all) {
|
||||
return []*types.TenantMember{}, nil
|
||||
}
|
||||
end := offset + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
return append([]*types.TenantMember(nil), all[offset:end]...), nil
|
||||
}
|
||||
|
||||
func (r *fakeTenantMemberRepo) UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error {
|
||||
if r.failUpdateRole != nil {
|
||||
return r.failUpdateRole
|
||||
|
||||
Reference in New Issue
Block a user