// Package companyquota resolves current organization limits and reserves // invitation or candidate-card usage in the caller's transaction. package companyquota import ( "context" "errors" "fmt" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) var ( ErrQuotaRepositoriesMissing = errors.New("company quota repositories are missing") ErrQuotaServiceUnavailable = errors.New("company quota service is unavailable") ) // Repositories is the transaction-scoped surface needed for one quota // operation. The service does not retain it, because the repositories are // bound to the caller's transaction. type Repositories interface { Policies() outbound.PolicyRepository CompanyQuotas() outbound.CompanyQuotaRepository } // Service reads the current policy and delegates the atomic reservation. It // stores only the application clock and is safe to reuse between calls. type Service struct { clock func() time.Time } // NewService takes the application clock used once per operation. A nil // clock is a wiring error and panics at construction. func NewService(clock func() time.Time) *Service { if clock == nil { panic("companyquota.NewService - clock must not be nil") } return &Service{clock: clock} } // ReserveInvitation atomically records a new invitation against the policy // effective at the operation's clock snapshot. The limit applies to the usage // scope of the organization: its own usage, or the holding pool at E0. Repeating // invitationID is idempotent even when the caller uses a different request key. func (service *Service) ReserveInvitation( ctx context.Context, repositories Repositories, organization domain.Organization, invitationID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { const location = "Service.ReserveInvitation" if invitationID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } quota, repository, err := service.resolve(ctx, repositories, organization, location) if err != nil { return outbound.CompanyQuotaDecision{}, err } decision, err := repository.ReserveInvitation(ctx, quota, invitationID) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve invitation usage: %w", location, err) } if !decision.RetryAt.IsZero() { decision.RetryAt = decision.RetryAt.UTC() } if err := validateDecision(quota, decision); err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err) } return decision, nil } // ReserveCardView atomically counts a distinct candidate in the rolling view // window of the organization's usage scope. A repeat within the window by the // same organization refreshes the stored time without charging another distinct // view. func (service *Service) ReserveCardView( ctx context.Context, repositories Repositories, organization domain.Organization, candidateID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { const location = "Service.ReserveCardView" if candidateID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } quota, repository, err := service.resolve(ctx, repositories, organization, location) if err != nil { return outbound.CompanyQuotaDecision{}, err } decision, err := repository.ReserveCardView(ctx, quota, candidateID) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - reserve card-view usage: %w", location, err) } if !decision.RetryAt.IsZero() { decision.RetryAt = decision.RetryAt.UTC() } if err := validateDecision(quota, decision); err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - validate reservation result: %w", location, err) } return decision, nil } func (service *Service) resolve( ctx context.Context, repositories Repositories, organization domain.Organization, location string, ) (domain.CompanyQuota, outbound.CompanyQuotaRepository, error) { if service == nil || service.clock == nil { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - service clock is missing: %w", location, ErrQuotaServiceUnavailable) } if repositories == nil { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repositories are missing: %w", location, ErrQuotaRepositoriesMissing) } policies := repositories.Policies() quotaRepository := repositories.CompanyQuotas() if policies == nil || quotaRepository == nil { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - transaction repository is missing: %w", location, ErrQuotaRepositoriesMissing) } now := service.clock().UTC() if now.IsZero() || now.Unix() < 0 { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - application clock must be set and non-negative: %w", location, domain.ErrInvalidCompanyQuota) } version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, now) if err != nil { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - read effective product policy: %w", location, err) } quota, err := domain.NewCompanyQuota(organization, version, now) if err != nil { return domain.CompanyQuota{}, nil, fmt.Errorf("%s - resolve organization quota: %w", location, err) } return quota, quotaRepository, nil } func validateDecision(quota domain.CompanyQuota, decision outbound.CompanyQuotaDecision) error { switch { case decision.Allowed && !decision.RetryAt.IsZero(): return errors.New("an allowed reservation cannot have a retry time") case decision.Reused && !decision.Allowed: return errors.New("a reused reservation must be allowed") case !decision.Allowed && (decision.Reused || decision.RetryAt.IsZero() || !decision.RetryAt.After(quota.At())): return errors.New("a denied reservation must be new and have a future retry time") } return nil }