refactor: fix 7 CRUD system inconsistencies for robustness and maintainability

- Add user-assignment dependency check to DepartmentService.deleteByUuid (409 when users assigned)
- Standardize POST detection to isMethod('POST') in 10 create/edit actions
- Align RoleService code uniqueness to warning pattern (matching departments)
- Normalize repository create() return types from mixed to int|false (3 repos + 3 interfaces)
- Add JSON response branches to 4 non-user delete actions
- Document delete authorization ordering pattern
- Decompose AdminSettingsService.updateFromAdmin into domain-scoped private methods

Workflow: .agents/runs/CRUD-CONSISTENCY-001/
Reviewed by: Code Reviewer (pass), Security Reviewer (pass), Acceptance Tester (pass)
Quality gates: QG-001 PHPUnit pass, QG-002 PHPStan pass, QG-003 Architecture pass

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-22 18:25:33 +01:00
parent 984d0430d3
commit c429ff43cd
29 changed files with 495 additions and 207 deletions

View File

@@ -56,7 +56,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$selectedTenantId = $request->bodyInt('tenant_id');
$selectedTenantIds = $directoryScopeGateway->filterTenantIdsForUser([$selectedTenantId], $currentUserId);
$selectedTenantId = (int) ($selectedTenantIds[0] ?? 0);

View File

@@ -1,5 +1,6 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
@@ -19,6 +20,11 @@ if ($uuid === '') {
$currentUserId = (int) ($session['user']['id'] ?? 0);
$department = app(\MintyPHP\Service\Org\DepartmentService::class)->findByUuid($uuid);
if (!$department) {
if (Request::wantsJson()) {
http_response_code(404);
Router::json(['error' => 'not_found']);
return;
}
Flash::error('Department not found', 'admin/departments', 'department_not_found');
Router::redirect('admin/departments');
return;
@@ -30,13 +36,29 @@ $decision = $authorizationService->authorize(DepartmentAuthorizationPolicy::ABIL
'target_department_id' => $departmentId,
]);
if (!$decision->isAllowed()) {
if (Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return;
}
Router::redirect('error/forbidden');
return;
}
$result = app(\MintyPHP\Service\Org\DepartmentService::class)->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
Flash::error('Department not found', 'admin/departments', 'department_not_found');
$error = $result['error'] ?? 'not_found';
$status = $result['status'] ?? 500;
if (Request::wantsJson()) {
http_response_code($status);
Router::json(['error' => $error]);
return;
}
if ($error === 'department_has_users') {
Flash::error(t('Department can not be deleted while users are assigned'), 'admin/departments', 'department_has_users');
} else {
Flash::error(t('Department not found'), 'admin/departments', 'department_not_found');
}
Router::redirect('admin/departments');
return;
}
@@ -45,5 +67,11 @@ if ($currentUserId > 0) {
app(\MintyPHP\Service\Auth\AuthService::class)->loadTenantDataIntoSession($currentUserId);
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
Flash::success('Department deleted', 'admin/departments', 'department_deleted');
Router::redirect('admin/departments');

View File

@@ -87,7 +87,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$submitDecision = $authorizationService->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_SUBMIT, [
'actor_user_id' => $currentUserId,
'target_department_id' => $departmentId,

View File

@@ -39,7 +39,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('key')) {
if ($request->isMethod('POST')) {
$result = app(\MintyPHP\Service\Access\PermissionService::class)->createFromAdmin($request->bodyAll());
$form = $result['form'] ?? $form;
$errorBag->merge($result['errors'] ?? []);

View File

@@ -1,5 +1,6 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionAuthorizationPolicy;
@@ -12,10 +13,18 @@ Guard::requireLogin();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
// Authorization is checked generically (can user delete ANY permission?) before loading the entity.
// Context-aware policies (departments, tenants, users) load the entity first to pass target_id.
// Both patterns are valid; context-aware is preferred for new code.
$decision = $authorizationService->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_DELETE, [
'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
if (Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return;
}
Guard::deny();
}
@@ -30,18 +39,31 @@ $affectedUserIds = app(\MintyPHP\Repository\Access\UserRoleRepository::class)->l
$result = app(PermissionService::class)->deleteById($id);
if (!($result['ok'] ?? false)) {
$error = (string) ($result['error'] ?? '');
$error = (string) ($result['error'] ?? 'not_found');
$status = $result['status'] ?? 500;
if (Request::wantsJson()) {
http_response_code($status);
Router::json(['error' => $error]);
return;
}
if ($error === 'system_permission_protected') {
Flash::error('System permission can not be deleted', 'admin/permissions', 'permission_system_protected');
} else {
Flash::error('Permission not found', 'admin/permissions', 'permission_not_found');
}
Router::redirect('admin/permissions');
return;
}
if ($affectedUserIds) {
app(\MintyPHP\Repository\User\UserWriteRepository::class)->bumpAuthzVersionByUserIds($affectedUserIds);
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
Flash::success('Permission deleted', 'admin/permissions', 'permission_deleted');
Router::redirect('admin/permissions');

View File

@@ -54,7 +54,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('key')) {
if ($request->isMethod('POST')) {
$submitDecision = $authorizationService->authorize(PermissionAuthorizationPolicy::ABILITY_ADMIN_PERMISSIONS_EDIT_SUBMIT, [
'actor_user_id' => $currentUserId,
'target_permission_id' => $id,

View File

@@ -26,6 +26,7 @@ if (!$decision->isAllowed()) {
$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = [
'description' => '',
'code' => '',
@@ -42,7 +43,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$dbSession = app(\MintyPHP\Repository\Support\DatabaseSessionRepository::class);
$transactionStarted = false;
@@ -52,6 +53,7 @@ if ($request->hasBody('description')) {
$result = app(\MintyPHP\Service\Access\RoleService::class)->createFromAdmin($request->bodyAll(), $currentUserId);
$form = $result['form'] ?? $form;
$warnings = $result['warnings'] ?? [];
$errorBag->merge($result['errors'] ?? []);
$selectedPermissionIds = $request->body('permission_ids', $selectedPermissionIds);
if (!is_array($selectedPermissionIds)) {
@@ -75,15 +77,24 @@ if ($request->hasBody('description')) {
$action = (string) $request->body('action', 'create');
if ($action === 'create_close') {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
}
Flash::success('Role created', $closeTarget, 'role_created');
Router::redirect($closeTarget);
} else {
$uuid = (string) ($result['uuid'] ?? '');
if ($uuid !== '') {
$target = requestPathWithReturnTarget("admin/roles/edit/{$uuid}", $returnTarget);
if ($warnings) {
Flash::info(implode(' ', $warnings), $target, 'role_warning');
}
Flash::success('Role created', $target, 'role_created');
Router::redirect($target);
} else {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
}
Flash::success('Role created', $closeTarget, 'role_created');
Router::redirect($closeTarget);
}

View File

@@ -42,6 +42,15 @@
$validationSummaryErrors = $validationSummaryErrors ?? ($errors ?? []);
require templatePath('partials/app-details-validation-summary.phtml');
?>
<?php if (!empty($warnings)): ?>
<div class="notice" data-variant="info">
<ul>
<?php foreach ($warnings as $warning): ?>
<li><?php e($warning); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php
$values = $form ?? [];
$detailsOpenAll = true;

View File

@@ -1,5 +1,6 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
@@ -11,10 +12,18 @@ Guard::requireLogin();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
// Authorization is checked generically (can user delete ANY role?) before loading the entity.
// Context-aware policies (departments, tenants, users) load the entity first to pass target_id.
// Both patterns are valid; context-aware is preferred for new code.
$decision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_DELETE, [
'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
if (Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return;
}
Guard::deny();
}
@@ -35,18 +44,31 @@ if ($role) {
$result = app(\MintyPHP\Service\Access\RoleService::class)->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
$error = $result['error'] ?? 'unknown';
$error = $result['error'] ?? 'not_found';
$status = $result['status'] ?? 500;
if (Request::wantsJson()) {
http_response_code($status);
Router::json(['error' => $error]);
return;
}
if ($error === 'admin_role_protected') {
Flash::error('The Admin role cannot be deleted', 'admin/roles', 'admin_role_protected');
} else {
Flash::error('Role not found', 'admin/roles', 'role_not_found');
}
Router::redirect('admin/roles');
return;
}
if ($affectedUserIds) {
app(\MintyPHP\Repository\User\UserWriteRepository::class)->bumpAuthzVersionByUserIds($affectedUserIds);
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
Flash::success('Role deleted', 'admin/roles', 'role_deleted');
Router::redirect('admin/roles');

View File

@@ -44,6 +44,7 @@ app(\MintyPHP\Service\Audit\AuditMetadataEnricher::class)->enrich($role);
$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = $role;
$permissions = $permissionRepository->listActive();
$selectedPermissionIds = $rolePermissionRepository->listPermissionIdsByRoleId($roleId);
@@ -58,7 +59,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$submitDecision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_EDIT_SUBMIT, [
'actor_user_id' => $currentUserId,
'target_role_id' => $roleId,
@@ -68,6 +69,7 @@ if ($request->hasBody('description')) {
}
$result = app(\MintyPHP\Service\Access\RoleService::class)->updateFromAdmin($roleId, $request->bodyAll(), $currentUserId);
$form = $result['form'] ?? $form;
$warnings = $result['warnings'] ?? [];
$errorBag->merge($result['errors'] ?? []);
$selectedPermissionIds = $request->body('permission_ids', $selectedPermissionIds);
if (!is_array($selectedPermissionIds)) {
@@ -108,9 +110,15 @@ if ($request->hasBody('description')) {
if ($syncSucceeded) {
$action = (string) $request->body('action', 'save');
if ($action === 'save_close') {
if ($warnings) {
Flash::info(implode(' ', $warnings), $closeTarget, 'role_warning');
}
Flash::success('Role updated', $closeTarget, 'role_updated');
Router::redirect($closeTarget);
} else {
if ($warnings) {
Flash::info(implode(' ', $warnings), $editTarget, 'role_warning');
}
Flash::success('Role updated', $editTarget, 'role_updated');
Router::redirect($editTarget);
}

View File

@@ -53,6 +53,15 @@ $isReadOnly = !$canUpdateRole;
$validationSummaryErrors = $validationSummaryErrors ?? ($errors ?? []);
require templatePath('partials/app-details-validation-summary.phtml');
?>
<?php if (!empty($warnings)): ?>
<div class="notice" data-variant="info">
<ul>
<?php foreach ($warnings as $warning): ?>
<li><?php e($warning); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php
$detailsOpenAll = true;

View File

@@ -62,7 +62,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$post = $request->bodyAll();
$ssoFields = [
'microsoft_enabled',

View File

@@ -1,5 +1,6 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
@@ -18,6 +19,11 @@ if ($uuid === '') {
$tenant = app(\MintyPHP\Service\Tenant\TenantService::class)->findByUuid($uuid);
if (!$tenant) {
if (Request::wantsJson()) {
http_response_code(404);
Router::json(['error' => 'not_found']);
return;
}
Flash::error('Tenant not found', 'admin/tenants', 'tenant_not_found');
Router::redirect('admin/tenants');
return;
@@ -30,13 +36,25 @@ $decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_
'target_tenant_id' => $tenantId,
]);
if (!$decision->isAllowed()) {
if (Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return;
}
Router::redirect('error/forbidden');
return;
}
$result = app(\MintyPHP\Service\Tenant\TenantService::class)->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
if (($result['error'] ?? '') === 'tenant_has_departments') {
$error = $result['error'] ?? 'not_found';
$status = $result['status'] ?? 500;
if (Request::wantsJson()) {
http_response_code($status);
Router::json(['error' => $error]);
return;
}
if ($error === 'tenant_has_departments') {
Flash::error('Tenant can not be deleted while departments are assigned', 'admin/tenants', 'tenant_has_departments');
Router::redirect('admin/tenants');
return;
@@ -51,5 +69,11 @@ if ($currentUserId > 0) {
app(\MintyPHP\Service\Auth\AuthService::class)->loadTenantDataIntoSession($currentUserId);
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
Flash::success('Tenant deleted', 'admin/tenants', 'tenant_deleted');
Router::redirect('admin/tenants');

View File

@@ -79,7 +79,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('description')) {
if ($request->isMethod('POST')) {
$post = $request->bodyAll();
$submitDecision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_EDIT_SUBMIT, [
'actor_user_id' => $currentUserId,

View File

@@ -105,7 +105,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('email')) {
if ($request->isMethod('POST')) {
$post = $request->bodyAll();
$input = $post;
$tenantIds = $canManageAssignments ? $userAssignmentService->normalizeIdInput($input['tenant_ids'] ?? []) : [];

View File

@@ -161,7 +161,7 @@ if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
return;
}
if ($request->hasBody('email')) {
if ($request->isMethod('POST')) {
$post = $request->bodyAll();
$submitDecision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_SUBMIT, [
'actor_user_id' => $currentUserId,