< Summary - Heimdall API

Information
Class: ArturRios.Heimdall.Query.Handlers.ListScopesQueryHandler
Assembly: ArturRios.Heimdall.Query
File(s): /home/runner/work/heimdall-api/heimdall-api/src/Application/ArturRios.Heimdall.Query/Handlers/ListScopesQueryHandler.cs
Line coverage
100%
Covered lines: 37
Uncovered lines: 0
Coverable lines: 37
Total lines: 100
Line coverage: 100%
Branch coverage
100%
Covered branches: 10
Total branches: 10
Branch coverage: 100%
Method coverage
100%
Covered methods: 2
Fully covered methods: 2
Total methods: 2
Method coverage: 100%
Full method coverage: 100%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
HandleAsync()100%1010100%

File(s)

/home/runner/work/heimdall-api/heimdall-api/src/Application/ArturRios.Heimdall.Query/Handlers/ListScopesQueryHandler.cs

#LineLine coverage
 1using ArturRios.Data.Relational.Core.Interfaces;
 2using ArturRios.Heimdall.Domain.Entities;
 3using ArturRios.Heimdall.Domain.Enums;
 4using ArturRios.Heimdall.Query.Input;
 5using ArturRios.Heimdall.Query.Output;
 6using ArturRios.Heimdall.Shared.Messages;
 7using ArturRios.Mediator.Query.Interfaces;
 8using ArturRios.Output;
 9using FluentValidation;
 10
 11namespace ArturRios.Heimdall.Query.Handlers;
 12
 13/// <summary>
 14///     Handles <see cref="ListScopesQuery" /> (UC-02 read b, FR-SC-03): lists scopes with pagination
 15///     and an optional name filter, excluding logically deleted scopes unless explicitly requested
 16///     (FR-SC-07). A System Admin lists every scope; a Scope Admin only the scopes they own.
 17/// </summary>
 18/// <remarks>
 19///     Ownership is read from the <c>SCOPE_OWNER</c> rows, never from the token's owned-scope claim:
 20///     that claim is a snapshot from sign-in, and an owner removed since (UC-22) must stop seeing the
 21///     scope at once rather than when their token expires. The filter runs before pagination, so the
 22///     total is the caller's own count — the number of other tenants' scopes stays out of reach, which
 23///     is why the listing used to be System-Admin-only.
 24/// </remarks>
 1625public class ListScopesQueryHandler(
 1626    IAsyncReadOnlyRepository<Scope, long> scopeReader,
 1627    IValidator<ListScopesQuery> validator)
 28    : IPaginatedQueryHandlerAsync<ListScopesQuery, ScopeOutput>
 29{
 30    public async Task<PaginatedOutput<ScopeOutput>> HandleAsync(ListScopesQuery query, CancellationToken cancellationTok
 31    {
 32        // NFR-10: page number/size bounds and filter length, validated before any query runs.
 1633        var validation = await validator.ValidateAsync(query);
 34
 1635        if (!validation.IsValid)
 36        {
 437            return PaginatedOutput<ScopeOutput>.New
 838                .WithErrors(validation.Errors.Select(failure => failure.ErrorMessage));
 39        }
 40
 1241        var scopes = scopeReader.Query();
 42
 43        // AF-02b (read b). Any other role is refused here as well as at the controller, so a role
 44        // added later cannot inherit the whole collection by default.
 1245        switch (query.ActingRole)
 46        {
 47            case (int)Roles.SystemAdmin:
 48                break;
 49            case (int)Roles.ScopeAdmin:
 450                scopes = scopes.Where(x => x.Owners.Any(owner => owner.Person.PublicId == query.ActingPersonId));
 451                break;
 52            default:
 153                return PaginatedOutput<ScopeOutput>.New.WithError(ScopeMessages.NotAuthorizedToListScopes);
 54        }
 55
 1156        if (!query.IncludeDeleted)
 57        {
 958            scopes = scopes.Where(x => !x.IsDeleted);
 59        }
 60
 61        // Compared case-insensitively (LOWER() in SQL), as the person listings do (FR-PE-04) and as
 62        // every name/email comparison in this codebase does.
 1163        if (!string.IsNullOrWhiteSpace(query.Name))
 64        {
 465            var name = query.Name.ToLower();
 466            scopes = scopes.Where(x => x.Name.ToLower().Contains(name));
 67        }
 68
 1169        var projected = scopes.Select(x => new ScopeOutput
 1170        {
 1171            Id = x.PublicId,
 1172            Name = x.Name,
 1173            Description = x.Description,
 1174            GoogleSignInEnabled = x.GoogleSignInEnabled,
 1175            SelfRegistrationEnabled = x.SelfRegistrationEnabled,
 1176            DefaultLegalBasis = x.DefaultLegalBasis,
 1177            PrivacyNoticeUri = x.PrivacyNoticeUri,
 1178            EmailVerificationUrl = x.EmailVerificationUrl,
 1179            PasswordResetUrl = x.PasswordResetUrl,
 1180            IsDeleted = x.IsDeleted,
 1181            OwnerIds = x.Owners.Select(owner => owner.Person.PublicId).ToList(),
 1182            CreatedAt = x.CreatedAt,
 1183            UpdatedAt = x.UpdatedAt
 1184        });
 85
 86        // Ordered by name with the public identifier as a tiebreaker, then paginated over that
 87        // ordering rather than handing PaginateAsync a sort key of its own.
 88        //
 89        // Name is not unique, and PostgreSQL gives no ordering guarantee between rows whose sort key
 90        // ties — each page is a separate query, free to break the tie differently. Two people called
 91        // "Ana Silva" straddling a page boundary could therefore appear on both pages while somebody
 92        // else appeared on neither. The tiebreaker makes the total order deterministic, so paging
 93        // through a list sees every row exactly once.
 1194        var ordered = projected.OrderBy(x => x.Name).ThenBy(x => x.Id);
 95
 1196        var output = await ordered.PaginateAsync(query.PageNumber, query.PageSize, orderBy: null);
 97
 1198        return output.WithMessage(ScopeMessages.ScopesRetrievedSuccessfully);
 1699    }
 100}