Files
breadcrumb-the-shire/pages/admin/tenants/delete($id).php

80 lines
2.4 KiB
PHP
Raw Normal View History

2026-02-04 23:31:53 +01:00
<?php
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
2026-02-04 23:31:53 +01:00
use MintyPHP\Router;
use MintyPHP\Service\Access\TenantAuthorizationPolicy;
2026-02-23 12:58:19 +01:00
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
2026-02-04 23:31:53 +01:00
$session = app(SessionStoreInterface::class)->all();
2026-02-04 23:31:53 +01:00
Guard::requireLogin();
2026-03-04 15:56:58 +01:00
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
2026-02-04 23:31:53 +01:00
$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
Router::redirect('admin/tenants');
return;
}
2026-03-04 15:56:58 +01:00
$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;
}
$currentUserId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) ($tenant['id'] ?? 0);
$decision = $authorizationService->authorize(TenantAuthorizationPolicy::ABILITY_ADMIN_TENANTS_DELETE, [
'actor_user_id' => $currentUserId,
'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;
2026-02-04 23:31:53 +01:00
}
2026-03-04 15:56:58 +01:00
$result = app(\MintyPHP\Service\Tenant\TenantService::class)->deleteByUuid($uuid);
2026-02-04 23:31:53 +01:00
if (!($result['ok'] ?? false)) {
$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;
}
2026-02-04 23:31:53 +01:00
Flash::error('Tenant not found', 'admin/tenants', 'tenant_not_found');
Router::redirect('admin/tenants');
return;
2026-02-04 23:31:53 +01:00
}
// Refresh session tenant data (removes deleted tenant, switches if it was current)
if ($currentUserId > 0) {
2026-03-04 15:56:58 +01:00
app(\MintyPHP\Service\Auth\AuthService::class)->loadTenantDataIntoSession($currentUserId);
2026-02-04 23:31:53 +01:00
}
if (Request::wantsJson()) {
http_response_code(204);
Router::json([]);
return;
}
2026-02-04 23:31:53 +01:00
Flash::success('Tenant deleted', 'admin/tenants', 'tenant_deleted');
Router::redirect('admin/tenants');