1
0

feat(core): UserProfileViewService + admin/users detail drawer

Extracts the user profile read-view into a core service + shared partial so
modules no longer duplicate the assignment/scope logic, and migrates the
admin/users list as the drawer's second consumer.

Consolidation:
- `core/Service/User/UserProfileViewService` owns the single read-path that
  resolves tenants/departments/roles for a user UUID, enforces scope-aware
  department visibility, and returns a consistent `{status, user}` shape.
- `templates/partials/app-user-profile.phtml` is the shared render template;
  takes `$profileKey` for storage namespace + lightbox grouping.
- `AddressBookService::buildViewContext()` shrinks to a one-line delegation
  and drops its `UserAssignmentService` dependency. The old
  `modules/addressbook/templates/address-book-profile.phtml` is removed.

admin/users migration:
- `pages/admin/users/view-fragment($id).php` + `(none).phtml` use the core
  service and enforce `ABILITY_ADMIN_USERS_VIEW`.
- `admin-users-index.js` replaces the grid-native `linkColumn` on the first
  name with a formatter that emits `data-drawer-trigger`; `linkColumn` is
  disabled so the drawer click handler wins. `fullUrl` points at the edit
  form — drawer → edit is one click.
- Drawer labels wired via page config.

The new `DetailDrawerFragmentContractTest` validated the users fragment
endpoint automatically — no manual test additions were needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-22 15:49:10 +02:00
parent 21c331cd06
commit c1cf9f94bb
13 changed files with 254 additions and 113 deletions

View File

@@ -22,9 +22,11 @@ use MintyPHP\Service\User\UserLifecycleRestoreService;
use MintyPHP\Service\User\UserLifecycleService;
use MintyPHP\Service\User\UserPasswordPolicyService;
use MintyPHP\Service\User\UserPasswordService;
use MintyPHP\Service\User\UserProfileViewService;
use MintyPHP\Service\User\UserRepositoryFactory;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Service\User\UserTenantContextService;
use MintyPHP\Service\Tenant\TenantScopeService;
final class UserRegistrar implements ContainerRegistrar
{
@@ -58,5 +60,11 @@ final class UserRegistrar implements ContainerRegistrar
$container->set(UserTenantRepository::class, static fn (AppContainer $c): UserTenantRepository => $c->get(UserRepositoryFactory::class)->createUserTenantRepository());
$container->set(UserRoleRepository::class, static fn (AppContainer $c): UserRoleRepository => $c->get(UserRepositoryFactory::class)->createUserRoleRepository());
$container->set(UserDepartmentRepository::class, static fn (AppContainer $c): UserDepartmentRepository => $c->get(UserRepositoryFactory::class)->createUserDepartmentRepository());
$container->set(UserProfileViewService::class, static fn (AppContainer $c): UserProfileViewService => new UserProfileViewService(
$c->get(UserAccountService::class),
$c->get(UserAssignmentService::class),
$c->get(TenantScopeService::class),
$c->get(UserAvatarService::class)
));
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace MintyPHP\Service\User;
use MintyPHP\Service\Tenant\TenantScopeService;
/**
* Builds the read-only profile view context shared by modules that render a
* user-profile card (address book detail, admin users quick-view drawer, etc.).
*
* The returned context is intentionally minimal and authorization-aware:
* departments and tenants are scoped to those the viewer also belongs to so
* org structure never leaks across tenants.
*/
class UserProfileViewService
{
public function __construct(
private readonly UserAccountService $userAccountService,
private readonly UserAssignmentService $userAssignmentService,
private readonly TenantScopeService $scopeGateway,
private readonly UserAvatarService $avatarService
) {
}
/**
* @return array{status: string, user?: array<string, mixed>}
*/
public function buildProfile(int $currentUserId, string $uuid): array
{
$uuid = trim($uuid);
if ($uuid === '') {
return ['status' => 'invalid_uuid'];
}
$user = $this->userAccountService->findByUuid($uuid);
if (!$user || !isset($user['id'])) {
return ['status' => 'not_found'];
}
$targetUserId = (int) $user['id'];
if ($targetUserId <= 0) {
return ['status' => 'not_found'];
}
// Users can always view their own profile; others require scope access.
if (
$currentUserId !== $targetUserId
&& !$this->scopeGateway->canAccess('users', $targetUserId, $currentUserId)
) {
return ['status' => 'forbidden'];
}
$viewerTenantIds = $this->normalizeIds($this->scopeGateway->getUserTenantIds($currentUserId));
$assignments = $this->userAssignmentService->buildAssignmentsForUser($targetUserId);
$departmentMap = [];
foreach (($assignments['departments'] ?? []) as $department) {
if (empty($department['active'])) {
continue;
}
$tenantId = (int) ($department['tenant_id'] ?? 0);
$label = trim((string) ($department['description'] ?? ''));
// Only show departments in tenants the viewer also belongs to — prevents leaking org structure.
if ($tenantId <= 0 || $label === '' || !in_array($tenantId, $viewerTenantIds, true)) {
continue;
}
$departmentMap[$tenantId] ??= [];
$departmentMap[$tenantId][] = $label;
}
foreach ($departmentMap as $tenantId => $labels) {
$labels = array_values(array_unique($labels));
natcasesort($labels);
$departmentMap[$tenantId] = array_values($labels);
}
$primaryTenantId = (int) ($user['primary_tenant_id'] ?? 0);
$tenantGroups = [];
foreach (($assignments['tenants'] ?? []) as $tenant) {
$tenantId = (int) ($tenant['id'] ?? 0);
$tenantLabel = trim((string) ($tenant['description'] ?? ''));
$status = strtolower(trim((string) ($tenant['status'] ?? '')));
if (
$tenantId <= 0
|| $tenantLabel === ''
|| $status !== 'active'
|| !in_array($tenantId, $viewerTenantIds, true)
) {
continue;
}
$tenantGroups[] = [
'label' => $tenantLabel,
'is_primary' => $primaryTenantId > 0 && $tenantId === $primaryTenantId,
'departments' => $departmentMap[$tenantId] ?? [],
];
}
usort($tenantGroups, static fn (array $a, array $b): int => strnatcasecmp(
(string) $a['label'],
(string) $b['label']
));
$roleLabels = [];
foreach (($assignments['roles'] ?? []) as $role) {
if (empty($role['active'])) {
continue;
}
$label = trim((string) ($role['description'] ?? ''));
if ($label !== '') {
$roleLabels[] = $label;
}
}
$roleLabels = array_values(array_unique($roleLabels));
natcasesort($roleLabels);
$roleLabels = array_values($roleLabels);
$avatarUuid = (string) ($user['uuid'] ?? '');
$user['has_avatar'] = $avatarUuid !== '' && $this->avatarService->hasAvatar($avatarUuid);
$user['tenant_groups'] = $tenantGroups;
$user['role_labels'] = $roleLabels;
return [
'status' => 'ok',
'user' => $user,
];
}
/**
* @param array<int, int|string> $values
* @return list<int>
*/
private function normalizeIds(array $values): array
{
$ids = array_values(array_unique(array_map('intval', $values)));
return array_values(array_filter($ids, static fn (int $id): bool => $id > 0));
}
}

View File

@@ -12,8 +12,8 @@ use MintyPHP\Service\Org\DepartmentService;
use MintyPHP\Service\Tenant\TenantScopeService;
use MintyPHP\Service\Tenant\TenantService;
use MintyPHP\Service\User\UserAccountService;
use MintyPHP\Service\User\UserAssignmentService;
use MintyPHP\Service\User\UserAvatarService;
use MintyPHP\Service\User\UserProfileViewService;
final class AddressBookContainerRegistrar implements ContainerRegistrar
{
@@ -25,13 +25,13 @@ final class AddressBookContainerRegistrar implements ContainerRegistrar
$container->set(AddressBookService::class, static fn (AppContainer $c): AddressBookService => new AddressBookService(
$c->get(UserAccountService::class),
$c->get(UserAssignmentService::class),
$c->get(TenantService::class),
$c->get(DepartmentService::class),
$c->get(RoleService::class),
$c->get(TenantScopeService::class),
$c->get(UserCustomFieldValueService::class),
$c->get(UserAvatarService::class)
$c->get(UserAvatarService::class),
$c->get(UserProfileViewService::class)
));
}
}

View File

@@ -9,20 +9,20 @@ use MintyPHP\Service\Org\DepartmentService;
use MintyPHP\Service\Tenant\TenantScopeService;
use MintyPHP\Service\Tenant\TenantService;
use MintyPHP\Service\User\UserAccountService;
use MintyPHP\Service\User\UserAssignmentService;
use MintyPHP\Service\User\UserAvatarService;
use MintyPHP\Service\User\UserProfileViewService;
class AddressBookService
{
public function __construct(
private readonly UserAccountService $userAccountService,
private readonly UserAssignmentService $userAssignmentService,
private readonly TenantService $tenantService,
private readonly DepartmentService $departmentService,
private readonly RoleService $roleService,
private readonly TenantScopeService $scopeGateway,
private readonly UserCustomFieldValueService $customFieldValueService,
private readonly UserAvatarService $avatarService
private readonly UserAvatarService $avatarService,
private readonly UserProfileViewService $userProfileViewService
) {
}
@@ -240,101 +240,7 @@ class AddressBookService
public function buildViewContext(int $currentUserId, string $uuid): array
{
$uuid = trim($uuid);
if ($uuid === '') {
return ['status' => 'invalid_uuid'];
}
$user = $this->userAccountService->findByUuid($uuid);
if (!$user || !isset($user['id'])) {
return ['status' => 'not_found'];
}
$targetUserId = (int) $user['id'];
if ($targetUserId <= 0) {
return ['status' => 'not_found'];
}
// Users can always view their own profile; others require scope access.
if (
$currentUserId !== $targetUserId
&& !$this->scopeGateway->canAccess('users', $targetUserId, $currentUserId)
) {
return ['status' => 'forbidden'];
}
$viewerTenantIds = $this->normalizeIds($this->scopeGateway->getUserTenantIds($currentUserId));
$assignments = $this->userAssignmentService->buildAssignmentsForUser($targetUserId);
$departmentMap = [];
foreach (($assignments['departments'] ?? []) as $department) {
if (empty($department['active'])) {
continue;
}
$tenantId = (int) ($department['tenant_id'] ?? 0);
$label = trim((string) ($department['description'] ?? ''));
// Only show departments in tenants the viewer also belongs to — prevents leaking org structure.
if ($tenantId <= 0 || $label === '' || !in_array($tenantId, $viewerTenantIds, true)) {
continue;
}
$departmentMap[$tenantId] ??= [];
$departmentMap[$tenantId][] = $label;
}
foreach ($departmentMap as $tenantId => $labels) {
$labels = array_values(array_unique($labels));
natcasesort($labels);
$departmentMap[$tenantId] = array_values($labels);
}
$primaryTenantId = (int) ($user['primary_tenant_id'] ?? 0);
$tenantGroups = [];
foreach (($assignments['tenants'] ?? []) as $tenant) {
$tenantId = (int) ($tenant['id'] ?? 0);
$tenantLabel = trim((string) ($tenant['description'] ?? ''));
$status = strtolower(trim((string) ($tenant['status'] ?? '')));
if (
$tenantId <= 0
|| $tenantLabel === ''
|| $status !== 'active'
|| !in_array($tenantId, $viewerTenantIds, true)
) {
continue;
}
$tenantGroups[] = [
'label' => $tenantLabel,
'is_primary' => $primaryTenantId > 0 && $tenantId === $primaryTenantId,
'departments' => $departmentMap[$tenantId] ?? [],
];
}
usort($tenantGroups, static fn (array $a, array $b): int => strnatcasecmp(
(string) $a['label'],
(string) $b['label']
));
$roleLabels = [];
foreach (($assignments['roles'] ?? []) as $role) {
if (empty($role['active'])) {
continue;
}
$label = trim((string) ($role['description'] ?? ''));
if ($label !== '') {
$roleLabels[] = $label;
}
}
$roleLabels = array_values(array_unique($roleLabels));
natcasesort($roleLabels);
$roleLabels = array_values($roleLabels);
$avatarUuid = (string) ($user['uuid'] ?? '');
$user['has_avatar'] = $avatarUuid !== '' && $this->avatarService->hasAvatar($avatarUuid);
$user['tenant_groups'] = $tenantGroups;
$user['role_labels'] = $roleLabels;
return [
'status' => 'ok',
'user' => $user,
];
return $this->userProfileViewService->buildProfile($currentUserId, $uuid);
}
/**

View File

@@ -1,2 +1,3 @@
<?php
require __DIR__ . '/../../templates/address-book-profile.phtml';
$profileKey = 'address-book-profile';
require templatePath('partials/app-user-profile.phtml');

View File

@@ -2,4 +2,5 @@
if (!isset($user) || !is_array($user)) {
return;
}
require __DIR__ . '/../../templates/address-book-profile.phtml';
$profileKey = 'address-book-profile';
require templatePath('partials/app-user-profile.phtml');

View File

@@ -9,8 +9,8 @@ use MintyPHP\Service\Org\DepartmentService;
use MintyPHP\Service\Tenant\TenantScopeService;
use MintyPHP\Service\Tenant\TenantService;
use MintyPHP\Service\User\UserAccountService;
use MintyPHP\Service\User\UserAssignmentService;
use MintyPHP\Service\User\UserAvatarService;
use MintyPHP\Service\User\UserProfileViewService;
use PHPUnit\Framework\TestCase;
class AddressBookServiceTest extends TestCase
@@ -18,13 +18,13 @@ class AddressBookServiceTest extends TestCase
public function testBuildIndexContextBuildsTenantDepartmentMapForGlobalScope(): void
{
$userAccountService = $this->createMock(UserAccountService::class);
$userAssignmentService = $this->createMock(UserAssignmentService::class);
$tenantService = $this->createMock(TenantService::class);
$departmentService = $this->createMock(DepartmentService::class);
$roleService = $this->createMock(RoleService::class);
$scopeGateway = $this->createMock(TenantScopeService::class);
$customFieldGateway = $this->createMock(UserCustomFieldValueService::class);
$avatarService = $this->createMock(UserAvatarService::class);
$userProfileViewService = $this->createMock(UserProfileViewService::class);
$scopeGateway
->expects($this->once())
@@ -67,13 +67,13 @@ class AddressBookServiceTest extends TestCase
]);
$service = new AddressBookService(
$userAccountService,
$userAssignmentService,
$tenantService,
$departmentService,
$roleService,
$scopeGateway,
$customFieldGateway,
$avatarService
$avatarService,
$userProfileViewService
);
$context = $service->buildIndexContext(7, []);

View File

@@ -141,6 +141,12 @@ $pageConfig = [
'bulkSendAccessConfirm' => t('Send access emails to selected users?'),
'bulkAccessPdfConfirm' => t('Generate access PDFs for selected users?'),
'primaryTenant' => t('Primary tenant'),
'drawerClose' => t('Close'),
'drawerPrev' => t('Previous'),
'drawerNext' => t('Next'),
'drawerOpenFull' => t('Open full page'),
'drawerLoading' => t('Loading'),
'drawerError' => t('Failed to load'),
'bulkMessages' => [
'activate' => [
'success' => t('%d users activated'),

View File

@@ -0,0 +1,45 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\AuthorizationService;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserProfileViewService;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
http_response_code(400);
return;
}
$decision = app(AuthorizationService::class)->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW, [
'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
http_response_code(403);
$user = null;
return;
}
$profile = app(UserProfileViewService::class)->buildProfile($currentUserId, $uuid);
$status = (string) ($profile['status'] ?? '');
if ($status === 'not_found' || $status === 'invalid_uuid') {
http_response_code(404);
$user = null;
return;
}
if ($status === 'forbidden') {
http_response_code(403);
$user = null;
return;
}
$user = $profile['user'] ?? null;
if (!is_array($user)) {
http_response_code(404);
$user = null;
return;
}

View File

@@ -0,0 +1,6 @@
<?php
if (!isset($user) || !is_array($user)) {
return;
}
$profileKey = 'admin-users-profile';
require templatePath('partials/app-user-profile.phtml');

View File

@@ -3,6 +3,10 @@
use MintyPHP\I18n;
$values = $user ?? [];
$profileKey = trim((string) ($profileKey ?? 'user-profile'));
if ($profileKey === '') {
$profileKey = 'user-profile';
}
$name = trim(($values['first_name'] ?? '') . ' ' . ($values['last_name'] ?? ''));
$displayName = $name !== '' ? $name : ($values['email'] ?? t('Address book'));
$email = trim((string) ($values['email'] ?? ''));
@@ -67,7 +71,7 @@ if ($profileDescription !== '') {
<div class="app-profile-header">
<div class="user-avatar-block avatar-round app-profile-avatar">
<?php if ($hasAvatar): ?>
<a data-fslightbox="address-book-avatar"
<a data-fslightbox="<?php e($profileKey); ?>-avatar"
href="admin/users/avatar-file?uuid=<?php e($avatarUuid); ?>&size=256">
<img class="user-avatar-image" src="admin/users/avatar-file?uuid=<?php e($avatarUuid); ?>&size=160"
alt="">
@@ -91,7 +95,7 @@ if ($profileDescription !== '') {
</div>
<div class="app-profile-body-container">
<div class="app-profile-body">
<div class="app-tabs" data-tabs data-app-component="tabs" data-tabs-param="tab" data-tabs-storage-key="address-book-profile">
<div class="app-tabs" data-tabs data-app-component="tabs" data-tabs-param="tab" data-tabs-storage-key="<?php e($profileKey); ?>">
<div class="app-tabs-nav">
<?php if ($hasContact): ?>
<button type="button" data-tab="contact" data-tab-default><small><?php e(t('Contact')); ?></small></button>

View File

@@ -41,7 +41,7 @@ class FrontendRuntimeHostContractTest extends TestCase
public function testTabsHostsUseDataAppComponentContract(): void
{
$files = [
'modules/addressbook/templates/address-book-profile.phtml',
'templates/partials/app-user-profile.phtml',
'pages/admin/departments/_form.phtml',
'pages/admin/permissions/_form.phtml',
'pages/admin/roles/_form.phtml',

View File

@@ -1,7 +1,8 @@
import { createListPageModule } from '../core/app-list-page-module.js';
import { initUsersListPage } from './app-users-list.js';
import { bindBulkVisibility } from '../components/app-bulk-selection.js';
import { buildUrl, badgeHtml, escapeHtml, buildBadgeList } from './app-list-utils.js';
import { initDetailDrawer } from '../components/app-detail-drawer.js';
import { buildUrl, badgeHtml, escapeHtml, buildBadgeList, withCurrentListReturn } from './app-list-utils.js';
import { showAsyncFlash, withLoading } from '../components/app-async-flash.js';
createListPageModule({
@@ -61,7 +62,17 @@ createListPageModule({
},
},
{ name: 'UUID', hidden: true },
{ name: labels.firstName || 'First name', sort: true },
{
name: labels.firstName || 'First name',
sort: true,
formatter: (cell, row) => {
const name = escapeHtml(String(cell || '').trim() || '-');
const uuid = row?.cells?.[uuidIndex]?.data;
if (!uuid) { return gridjs.html(`<span>${name}</span>`); }
const editUrl = escapeHtml(withCurrentListReturn(new URL(`admin/users/edit/${uuid}`, appBase).toString()));
return gridjs.html(`<a class="app-grid-link-cell" href="${editUrl}" data-drawer-trigger>${name}</a>`);
},
},
{ name: labels.lastName || 'Last name', sort: true },
{ name: labels.email || 'Email', sort: true },
{
@@ -140,7 +151,7 @@ createListPageModule({
rowDataset: (row) => ({
uuid: row?.cells?.[uuidIndex]?.data,
}),
rowInteraction: { linkColumn: 2 },
rowInteraction: { linkColumn: false },
rowDblClick: {
getUrl: (rowData) => {
if (!canEditRow(rowData)) {
@@ -190,6 +201,23 @@ createListPageModule({
buttonSelector: '[data-users-bulk]',
});
initDetailDrawer({
gridConfig,
triggerSelector: '[data-drawer-trigger]',
rowUuidAttr: 'uuid',
fetchUrl: (uuid) => new URL(`admin/users/view-fragment/${uuid}`, appBase).toString(),
fullUrl: (uuid) => withCurrentListReturn(new URL(`admin/users/edit/${uuid}`, appBase).toString()),
hashPrefix: 'user',
labels: {
close: labels.drawerClose || 'Close',
previous: labels.drawerPrev || 'Previous',
next: labels.drawerNext || 'Next',
openFull: labels.drawerOpenFull || 'Open full page',
loading: labels.drawerLoading || 'Loading',
error: labels.drawerError || 'Failed to load',
},
});
return usersGridConfig;
},
});