find($id); return $model === null ? null : $this->toEntity($model); } public function findByEmail(EmailAddress $email): ?UserAccount { $model = User::query()->where('email', $email->value)->first(); return $model === null ? null : $this->toEntity($model); } public function save(UserAccount $user): UserAccount { if ($user->id() === null) { $model = new User; // Nobody knows this password: the user sets their own through the emailed link. $model->password = Str::random(64); } else { $model = User::query()->findOrFail($user->id()); } $model->fill([ 'name' => $user->name()->value, 'email' => $user->email()->value, 'role' => $user->role(), 'is_active' => $user->isActive(), 'employment_ends_on' => $user->employmentEndsOn()?->format('Y-m-d'), 'supervisor_id' => $user->supervisorId(), ])->save(); UserMoneyPermissionsModel::query()->updateOrCreate( ['user_id' => $model->id], UserMoneyPermissionsModel::columnsFor($user->moneyPermissions()), ); $model->unsetRelation('moneyPermissions'); return $this->toEntity($model->refresh()); } public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool { return User::query() ->where('email', $email->value) ->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId)) ->exists(); } public function countActiveAdmins(?int $exceptUserId = null): int { // Lock every active admin row (in id order, so concurrent callers queue // instead of deadlocking); the second caller then sees the first one's change. $adminIds = User::query() ->where('role', Role::Admin) ->where('is_active', true) ->orderBy('id') ->lockForUpdate() ->pluck('id'); return $adminIds->reject(fn (int $id): bool => $id === $exceptUserId)->count(); } public function countActiveInternsSupervisedBy(int $supervisorId): int { return User::query() ->where('role', Role::Intern) ->where('is_active', true) ->where('supervisor_id', $supervisorId) ->count(); } private function toEntity(User $model): UserAccount { return UserAccount::reconstitute( $model->id, new PersonName($model->name), new EmailAddress($model->email), $model->role, $model->is_active, $model->employment_ends_on === null ? null : DateTimeImmutable::createFromInterface($model->employment_ends_on), $model->supervisor_id, $model->moneyPermissions?->permissions() ?? [], ); } }