Hamsayeh Notes 2: "Manager" is not a column

Hamsayeh Notes 2:

On the day the first code landed, UserRole in Hamsayeh had three values: Admin, Builder and Resident. One person had one role, stored on the user row and carried in the token. A building management product strains that model early, because a person can live in one building, manage another and also operate the system. Management passes from one person to the next as well, and the records have to survive the handover.

The case study page says only that roles depend on the building. Getting there took several changes between April and June, and one piece of data moved twice in six days. The second half of this post covers a related problem: an API split by audience, for an audience that shares its pages.

What the old model could not say

A checklist added on 5 April, the day the rework began, names the problems. User.Role was "a single global role". Building.CreatedByUserId was used "as both creation metadata and active access control". Resident access was inferred from active unit memberships, and the token exposed one role.

The same file sets the target. One person can hold several assignments at once across buildings, a building can have several managers at the same time, and resident history is kept as date ranges that can be queried with asOfUtc. It also says to keep building history immutable when management is transferred "by ending one assignment and creating another". The volunteer manager persona asks for the same thing in product language: handover to the new manager with all records kept.

Two homes for a building role

On 5 April, four commits in about two and a half hours made the first move. UserAccessAssignment arrived as a time-bound record with a backfill migration (13 files, 2,642 inserted lines). Sessions switched to access snapshots, building management was resolved from temporal assignments, and the front end adopted the snapshots. On 7 April the enum shrank to Admin and User.

On 11 April building roles moved again, into their own BuildingRole aggregate and table, and UserAccessAssignment was left with system-level access only. That commit touched 35 files. Its message describes the result and mentions encapsulation. It does not record what was wrong with a design that was six days old. The aggregate looks like this, trimmed to the fields that matter here:

public sealed class BuildingRole : AggregateRoot
{
    public Guid BuildingId { get; private set; }
    public Guid UserId { get; private set; }
    public BuildingRoleType RoleType { get; private set; }
    public Guid? GrantedByUserId { get; private set; }
    public Guid? EndedByUserId { get; private set; }
    public DateTime EffectiveFromUtc { get; private set; }
    public DateTime? EffectiveToUtc { get; private set; }

    public bool IsActiveAt(DateTime atUtc)
        => EffectiveFromUtc <= atUtc && (!EffectiveToUtc.HasValue || EffectiveToUtc > atUtc);
}

BuildingRoleType has two values, Manager and BoardMember. Being a resident is a separate fact, held on UnitMembership with its own move-in and leaving dates. So one person in one building can have a role row, a membership row, both or neither, and AuthAccessSnapshotFactory combines those sources for a given moment, along with system assignments and organization links.

Transfer works the way the checklist asked. A handler ends the current role and creates a new one for the replacement, so the old row stays as history. The overlap check runs per person, building and role type, which lets two different people manage one building at the same time. That check lives in application code. The indexes on the table are not unique, so nothing in the database stops two overlapping rows for the same person if two writes race.

A controller with no [Authorize]

Between those two moves, on 9 April, a commit separating system-admin and building-manager access recorded that SystemAdminsAdminController "was missing [Authorize] entirely". As far as the code at that commit shows, requests were still refused: reading the current user id failed with a 401 for an anonymous caller, and all five handlers behind the controller checked for the system admin role. What was missing was the declaration at the HTTP layer. The commit added [Authorize(Roles = "Admin")] and raised four other system controllers from plain [Authorize] to the same role. The attribute is on that controller today.

The checklist had pointed the other way, planning to replace [Authorize(Roles = ...)] with authenticated access plus application-level checks. The code ended up with both. System controllers such as this one carry role attributes, and handlers re-check building access through helpers such as AdminAccessHelper, TicketAccessHelper and DocumentAccessScopeResolver.

The assumption that survived

The checklist named CreatedByUserId on 5 April, yet the idea behind it lasted until late May. Everyone registering was treated as a future manager, and whoever created a building was treated as its permanent manager. A waiting page replaced the auto-manager assumption on 19 May. On 21 May another commit closed the rest, and its message states the old behaviour: three repository methods "treated any creator as a permanent manager regardless of their chosen role". The same message gives the effect of the fix: "A resident who created the building can no longer reach the admin panel after a page refresh."

I checked the current query, and creator access now applies only while IsOnboardingComplete is false. During that period the snapshot factory synthesizes manager access. After it, only an explicit active manager role counts. Part 3 covers the wizard that needs this.

Roles granted by someone else have one more rule:

public static bool RequiresAcceptance(BuildingRole role)
    => role.GrantedByUserId.HasValue && role.GrantedByUserId.Value != role.UserId;

public static bool IsAccepted(BuildingRole role, IReadOnlyDictionary<Guid, DateTime?> lastLoginByUser)
    => !RequiresAcceptance(role)
        || (lastLoginByUser.TryGetValue(role.UserId, out var lastLoginAtUtc)
            && lastLoginAtUtc.HasValue
            && lastLoginAtUtc.Value >= role.EffectiveFromUtc
            && lastLoginAtUtc.Value >= role.CreatedAtUtc);

Such a role reports as Pending until the person logs in successfully at or after the grant, then Active, then Ended. So acceptance here means a later login. This helper has no separate accept action, and a login for any other reason counts too.

The rule used to sit inline in three repository queries, joining login activity from the identity context inside a building query. A commit on 4 June replaced that with three steps: load candidate roles, load login times, filter in memory. Its message gives no reason. As far as the diff shows, one LINQ expression across two contexts became separate reads, and part 4 covers what the context split cost elsewhere. The rule now exists twice, in BuildingRoleAcceptanceHelper and in a private IsAcceptedRole method in BuildingRepository, as two separate pieces of code.

Two hosts, one set of pages

At 23:08 on 10 April the single API became Hamsayeh.Api.Admin and Hamsayeh.Api.User, with shared plumbing in Hamsayeh.Api.Shared. The commit touched 80 files and described the split as "Api.Admin for SystemAdmin, Api.User for BuildingManager/residents".

The first correction came 35 minutes later: "SubscriptionController was only in Admin API but BuildingManagers need it". The second came at 00:07, moving dashboard and access-status endpoints because the dashboard and pending payment pages "are accessible to BuildingManagers (no requiredScope="system") but were calling Admin API endpoints".

The cause sits in the front end. The management portal is one code base serving system admins and building managers, separated by a scope:

export type AdminAccessScope = 'building' | 'system'

A route marked requiredScope with the system scope redirects building managers away. The guard is a redirect and proves nothing on the server. It did record which pages were system-only, and any page without it belonged to managers as well, whatever folder it sat in. Those pages could not get their data from a host described as being for system admins.

Counting HTTP method attributes by grep, where an action with two attributes counts twice, Api.Admin today has 8 controllers and 30 attributes, and Api.User has 27 controllers and 209. Almost all of the management portal's data lives on the User API, under a building-manager route prefix since 9 May. As far as the code shows, the hosts ended up closer to "system operator versus everyone else" than to "admin portal versus building portal". The page-level scope was the boundary that mattered, and the hosts had to follow it.

Auth was duplicated as controllers in both hosts until 15 May, when eight Minimal API routes in Api.Shared replaced them, mapped into both hosts (5 files, 149 lines added, 228 removed). The front end's clients show the result in three lines:

export const adminApiClient = createApiClient(ADMIN_API_BASE_URL)
export const userApiClient = createApiClient(USER_API_BASE_URL)
export const buildingApiClient = userApiClient

A build script, check-default-api-client-imports.mjs, rejects default imports of the client, so every feature has to name the one it uses. That makes the choice visible in review. It cannot tell whether the choice is right, and a page pointed at the wrong host would still pass.

What is unfinished

The checklist said User.Role "must be removed from domain, auth, and UI assumptions". It was not removed. The enum is smaller and it still takes part in system-level checks, so the old model and the new one coexist in that corner.

Test evidence for all this is modest. AuthAccessSnapshotFactoryTests has three tests: a manager without a resident membership, a resident, and a person with no access yet. Four security scenarios and one cross-portal access test exist as Playwright specs. The repository holds no CI results, and part 7 returns to what the tests do and do not prove.

Part 3 moves to the onboarding wizard, where the waiting page came from and where much of May went.

This note is also available in Persian: read the Persian version.

Back to all notes