1
0

refactor(audit): extract audit domain into self-contained module

Move the entire audit subsystem (system audit, API audit, import audit,
user lifecycle audit, frontend telemetry) from core into modules/audit/.

Core decoupling via interface-based injection:
- AuditRecorderInterface replaces SystemAuditService in 10+ core services
- UserLifecycleAuditInterface / ImportAuditInterface for specialized flows
- NullAuditRecorder fallback when audit module is disabled
- ApiBootstrap/ApiResponse use null-safe callable resolvers

Module structure (modules/audit/):
- Manifest with routes, permissions, scheduler jobs, authorization policy
- 9 services, 8 repositories, 6 domain enums, 4 job handlers
- 33 page files, 4 JS files, 8 test files, migration scripts, i18n

Core cleanup:
- OperationsAuthorizationPolicy, UiCapabilityMap, PermissionService
  surgically cleaned of audit-specific constants
- Sidebar template cleared of hardcoded audit navigation
- AuditModuleIsolationContractTest ensures no future core→module coupling

All quality gates pass: 1346 tests (19,276 assertions), PHPStan level 5
clean, architecture contracts verified.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-25 21:12:49 +01:00
parent 12a837bda9
commit 0c351f6aff
176 changed files with 2157 additions and 834 deletions

View File

@@ -1,48 +0,0 @@
<?php
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_API_AUDIT_VIEW);
gridRequireGetRequest();
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$result = app(\MintyPHP\Service\Audit\ApiAuditService::class)->listPaged($filters);
$rows = [];
foreach ($result['rows'] as $row) {
$statusCode = (int) ($row['status_code'] ?? 0);
$statusBadge = gridResolveBadgeVariant(
$statusCode >= 500 ? '5xx' : ($statusCode >= 400 ? '4xx' : ($statusCode >= 200 ? '2xx' : 'other')),
['2xx' => 'success', '4xx' => 'warning', '5xx' => 'danger']
);
$userLabel = trim((string) ($row['user_display_name'] ?? ''));
$userEmail = trim((string) ($row['user_email'] ?? ''));
if ($userLabel === '') {
$userLabel = $userEmail !== '' ? $userEmail : '-';
}
$rows[] = [
'id' => (int) ($row['id'] ?? 0),
'request_id' => (string) ($row['request_id'] ?? ''),
'created_at' => dt((string) ($row['created_at'] ?? '')),
'method' => strtoupper((string) ($row['method'] ?? '')),
'path' => (string) ($row['path'] ?? ''),
'status_code' => $statusCode,
'status_badge' => $statusBadge,
'duration_ms' => (int) ($row['duration_ms'] ?? 0),
'error_code' => (string) ($row['error_code'] ?? ''),
'tenant_id' => (int) ($row['tenant_id'] ?? 0),
'tenant_label' => (string) ($row['tenant_description'] ?? ''),
'tenant_uuid' => (string) ($row['tenant_uuid'] ?? ''),
'user_id' => (int) ($row['user_id'] ?? 0),
'user_label' => $userLabel,
'user_uuid' => (string) ($row['user_uuid'] ?? ''),
'ip' => (string) ($row['ip'] ?? ''),
];
}
gridJsonDataResult($rows, (int) ($result['total'] ?? 0));

View File

@@ -1,93 +0,0 @@
<?php
return gridFilterSchema([
'query' => [
'limit' => ['type' => 'int', 'default' => 20, 'min' => 1, 'max' => 200],
'offset' => ['type' => 'int', 'default' => 0, 'min' => 0],
'search' => ['type' => 'string'],
'status' => ['type' => 'string'],
'method' => ['type' => 'enum', 'allowed' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], 'default' => ''],
'created_from' => ['type' => 'date'],
'created_to' => ['type' => 'date'],
'tenant_ids' => ['type' => 'csv_ids', 'max' => 200],
'user_ids' => ['type' => 'csv_ids', 'max' => 200],
'order' => ['type' => 'order', 'allowed' => ['created_at', 'status_code', 'method', 'path', 'duration_ms'], 'default' => 'created_at'],
'dir' => ['type' => 'dir', 'default' => 'desc'],
],
'toolbar' => [
[
'key' => 'search',
'type' => 'text',
'label' => 'Search',
'placeholder' => 'Search...',
'input_id' => 'api-audit-search',
'search' => true,
'query' => ['type' => 'string'],
],
[
'key' => 'status',
'type' => 'select',
'label' => 'Status',
'input_id' => 'api-audit-status-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All statuses'],
['id' => '2xx', 'description' => '2xx', 'translate' => false],
['id' => '4xx', 'description' => '4xx', 'translate' => false],
['id' => '5xx', 'description' => '5xx', 'translate' => false],
['id' => '401', 'description' => '401', 'translate' => false],
['id' => '403', 'description' => '403', 'translate' => false],
['id' => '404', 'description' => '404', 'translate' => false],
['id' => '422', 'description' => '422', 'translate' => false],
['id' => '500', 'description' => '500', 'translate' => false],
],
],
[
'key' => 'method',
'type' => 'select',
'label' => 'Method',
'input_id' => 'api-audit-method-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All methods'],
['id' => 'GET', 'description' => 'GET', 'translate' => false],
['id' => 'POST', 'description' => 'POST', 'translate' => false],
['id' => 'PUT', 'description' => 'PUT', 'translate' => false],
['id' => 'PATCH', 'description' => 'PATCH', 'translate' => false],
['id' => 'DELETE', 'description' => 'DELETE', 'translate' => false],
],
],
[
'key' => 'created_from',
'type' => 'date',
'label' => 'Created from',
'input_id' => 'api-audit-created-from',
],
[
'key' => 'created_to',
'type' => 'date',
'label' => 'Created to',
'input_id' => 'api-audit-created-to',
],
[
'key' => 'tenant_ids',
'type' => 'multi_csv',
'label' => 'Tenants',
'placeholder' => 'Select tenants',
'input_id' => 'api-audit-tenant-ids-filter',
'options_key' => 'tenant_items',
'default' => [],
'query' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'user_ids',
'type' => 'multi_csv',
'label' => 'Users',
'placeholder' => 'Select users',
'input_id' => 'api-audit-user-ids-filter',
'options_key' => 'user_items',
'default' => [],
'query' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
],
],
]);

View File

@@ -1,15 +0,0 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Support\Guard;
Guard::requireLogin();
$slug = trim((string) ($slug ?? ''));
if ($slug === '') {
require __DIR__ . '/index().php';
return;
}
Router::redirect('error/not_found?url=' . urlencode(Request::pathWithQuery()));

View File

@@ -1,160 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\ApiAuditService;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_API_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_AUDIT_PURGE
);
Buffer::set('title', t('API audit logs'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
...gridSchemaQuery($filterSchema),
'tenant_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
'user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(ApiAuditService::class)->filterOptions(200);
$activeTenantIds = array_map('strval', is_array($filterState['tenant_ids'] ?? null) ? $filterState['tenant_ids'] : []);
$activeUserIds = array_map('strval', is_array($filterState['user_ids'] ?? null) ? $filterState['user_ids'] : []);
$apiAuditTenantItems = [];
foreach ((array) ($filterOptions['tenants'] ?? []) as $tenantOption) {
if (!is_array($tenantOption)) {
continue;
}
$tenantId = (int) ($tenantOption['id'] ?? 0);
if ($tenantId <= 0) {
continue;
}
$tenantLabel = trim((string) ($tenantOption['description'] ?? ''));
$tenantExists = (bool) ($tenantOption['exists'] ?? false);
if ($tenantLabel === '') {
$tenantLabel = $tenantExists
? sprintf(t('Tenant #%d'), $tenantId)
: sprintf(t('Tenant #%d (deleted)'), $tenantId);
}
$id = (string) $tenantId;
$apiAuditTenantItems[$id] = [
'id' => $id,
'description' => $tenantLabel,
];
}
foreach ($activeTenantIds as $tenantId) {
if (!isset($apiAuditTenantItems[$tenantId])) {
$apiAuditTenantItems[$tenantId] = [
'id' => $tenantId,
'description' => sprintf(t('Tenant #%d (deleted)'), (int) $tenantId),
];
}
}
$apiAuditTenantItems = array_values($apiAuditTenantItems);
$apiAuditUserItems = [];
foreach ((array) ($filterOptions['users'] ?? []) as $userOption) {
if (!is_array($userOption)) {
continue;
}
$userId = (int) ($userOption['id'] ?? 0);
if ($userId <= 0) {
continue;
}
$userDisplayName = trim((string) ($userOption['display_name'] ?? ''));
$userEmail = trim((string) ($userOption['email'] ?? ''));
$userExists = (bool) ($userOption['exists'] ?? false);
$userLabel = $userDisplayName !== '' ? $userDisplayName : $userEmail;
if ($userLabel === '') {
$userLabel = $userExists
? sprintf(t('User #%d'), $userId)
: sprintf(t('User #%d (deleted)'), $userId);
}
$id = (string) $userId;
$apiAuditUserItems[$id] = [
'id' => $id,
'description' => $userLabel,
];
}
foreach ($activeUserIds as $userId) {
if (!isset($apiAuditUserItems[$userId])) {
$apiAuditUserItems[$userId] = [
'id' => $userId,
'description' => sprintf(t('User #%d (deleted)'), (int) $userId),
];
}
}
$apiAuditUserItems = array_values($apiAuditUserItems);
$toolbarFilterState = [
'search' => (string) ($filterState['search'] ?? ''),
'status' => (string) ($filterState['status'] ?? ''),
'method' => (string) ($filterState['method'] ?? ''),
'created_from' => (string) ($filterState['created_from'] ?? ''),
'created_to' => (string) ($filterState['created_to'] ?? ''),
'tenant_ids' => $activeTenantIds,
'user_ids' => $activeUserIds,
];
$toolbarOptionSets = [
'tenant_items' => $apiAuditTenantItems,
'user_items' => $apiAuditUserItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
'filter_state' => $filterState,
'search_keys' => ['search'],
'toolbar_state_overrides' => $toolbarFilterState,
'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
'search' => [
'label' => t('Search'),
'type' => 'text',
],
'status' => [
'label' => t('Status'),
'type' => 'select',
'default' => (string) (($schemaByKey['status']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
],
'method' => [
'label' => t('Method'),
'type' => 'select',
'default' => (string) (($schemaByKey['method']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['method'] ?? [])),
],
'tenant_ids' => [
'label' => t('Tenants'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($apiAuditTenantItems),
],
'user_ids' => [
'label' => t('Users'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($apiAuditUserItems),
],
'created_range' => [
'label' => t('Created'),
'type' => 'date_range',
'from_param' => 'created_from',
'to_param' => 'created_to',
],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];

View File

@@ -1,69 +0,0 @@
<?php
$pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canPurgeApiAudit = (bool) ($pageAuth['can_purge'] ?? false);
$toolbarFilterSchema = is_array($toolbarFilterSchema ?? null) ? $toolbarFilterSchema : [];
$searchToolbarFilterSchema = is_array($searchToolbarFilterSchema ?? null) ? $searchToolbarFilterSchema : [];
$drawerToolbarFilterSchema = is_array($drawerToolbarFilterSchema ?? null) ? $drawerToolbarFilterSchema : [];
$toolbarFilterState = is_array($toolbarFilterState ?? null) ? $toolbarFilterState : [];
$toolbarOptionSets = is_array($toolbarOptionSets ?? null) ? $toolbarOptionSets : [];
$filterChipMeta = is_array($filterChipMeta ?? null) ? $filterChipMeta : [];
$clientFilterSchema = is_array($clientFilterSchema ?? null) ? $clientFilterSchema : [];
$searchConfig = is_array($searchConfig ?? null) ? $searchConfig : null;
?>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('API audit logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<?php
$listTitle = t('API audit logs');
ob_start();
?>
<?php
$listPurgeEnabled = $canPurgeApiAudit;
$listPurgeFormId = 'api-audit-purge-form';
$listPurgeAction = 'admin/api-audit/purge';
$listPurgeConfirmMessage = t('Purge entries older than 90 days?');
$listPurgeButtonLabel = t('Purge API audit logs');
require templatePath('partials/app-list-purge-action.phtml');
?>
<?php
$listTitleActionsHtml = ob_get_clean();
require templatePath('partials/app-list-titlebar.phtml');
?>
<?php
$filterUiNamespace = 'api-audit';
require templatePath('partials/app-list-filters.phtml');
?>
<div class="app-list-table">
<div id="api-audit-grid"></div>
</div>
<?php
$gridLang = json_decode(appBufferValue('grid_lang'), true);
if (!is_array($gridLang)) {
$gridLang = [];
}
$pageConfig = [
'gridSearch' => $searchConfig,
'filterSchema' => $clientFilterSchema,
'filterChipMeta' => $filterChipMeta,
'gridLang' => $gridLang,
'labels' => [
'created' => t('Created'),
'statusCode' => t('Status code'),
'method' => t('Method'),
'path' => t('Path'),
'durationMs' => t('Duration (ms)'),
'user' => t('User'),
'tenant' => t('Tenant'),
'errorCode' => t('Error code'),
'ip' => t('IP'),
],
];
?>
<script src="<?php e(assetVersion('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="application/json" id="page-config-admin-api-audit-index"><?php gridJsonForJs($pageConfig); ?></script>
<script type="module" src="<?php e(assetVersion('js/pages/admin-api-audit-index.js')); ?>"></script>

View File

@@ -1,23 +0,0 @@
<?php
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE);
if (strtoupper((string) (requestInput()->method())) !== 'POST') {
Router::redirect('admin/api-audit');
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, 'admin/api-audit', 'api_audit');
Router::redirect('admin/api-audit');
}
$deleted = app(\MintyPHP\Service\Audit\ApiAuditService::class)->purgeExpired();
Flash::success(sprintf(t('%d API audit entries purged'), $deleted), 'admin/api-audit', 'api_audit_purged');
Router::redirect('admin/api-audit');

View File

@@ -1,18 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_API_AUDIT_VIEW);
$auditId = (int) ($id ?? 0);
$auditLog = $auditId > 0 ? app(\MintyPHP\Service\Audit\ApiAuditService::class)->find($auditId) : null;
if (!$auditLog) {
Flash::error('API audit entry not found', 'admin/api-audit', 'api_audit_not_found');
Router::redirect('admin/api-audit');
}
Buffer::set('title', t('View API audit entry'));

View File

@@ -1,193 +0,0 @@
<?php
/**
* @var array $auditLog
*/
$auditLog = $auditLog ?? [];
$statusCode = (int) ($auditLog['status_code'] ?? 0);
$statusVariant = 'neutral';
if ($statusCode >= 200 && $statusCode < 300) {
$statusVariant = 'success';
} elseif ($statusCode >= 400 && $statusCode < 500) {
$statusVariant = 'warning';
} elseif ($statusCode >= 500) {
$statusVariant = 'danger';
}
$queryJson = trim((string) ($auditLog['query_json'] ?? ''));
$queryPretty = '-';
if ($queryJson !== '') {
$decoded = json_decode($queryJson, true);
if (is_array($decoded)) {
$pretty = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$queryPretty = is_string($pretty) ? $pretty : $queryJson;
} else {
$queryPretty = $queryJson;
}
}
$userLabel = trim((string) ($auditLog['user_display_name'] ?? ''));
$userEmail = trim((string) ($auditLog['user_email'] ?? ''));
if ($userLabel === '') {
$userLabel = $userEmail !== '' ? $userEmail : '-';
}
$tenantLabel = trim((string) ($auditLog['tenant_description'] ?? ''));
if ($tenantLabel === '') {
$tenantLabel = '-';
}
$requestId = trim((string) ($auditLog['request_id'] ?? ''));
$method = strtoupper(trim((string) ($auditLog['method'] ?? '')));
$path = trim((string) ($auditLog['path'] ?? ''));
$errorCode = trim((string) ($auditLog['error_code'] ?? ''));
$ip = trim((string) ($auditLog['ip'] ?? ''));
$userAgent = trim((string) ($auditLog['user_agent'] ?? ''));
$durationMs = (int) ($auditLog['duration_ms'] ?? 0);
$tokenId = (int) ($auditLog['api_token_id'] ?? 0);
$tokenTenantId = (int) ($auditLog['token_tenant_id'] ?? 0);
?>
<div class="app-details-container">
<section>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('API audit logs'), 'path' => 'admin/api-audit'],
['label' => t('View')],
];
require templatePath('partials/app-breadcrumb.phtml');
$titlebar = [
'title' => t('View API audit entry'),
'backHref' => 'admin/api-audit',
'backTitle' => t('Back'),
];
require templatePath('partials/app-details-titlebar.phtml');
?>
<div class="app-details-content">
<details open>
<summary><?php e(t('Request details')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Method')); ?></small>
<p><span class="badge" data-variant="neutral"><?php e($method !== '' ? $method : '-'); ?></span></p>
</div>
<div>
<small><?php e(t('Path')); ?></small>
<p><code><?php e($path !== '' ? $path : '-'); ?></code></p>
</div>
</div>
<?php if ($errorCode !== '' || $ip !== ''): ?>
<div class="grid">
<div>
<small><?php e(t('Error code')); ?></small>
<p><?php e($errorCode !== '' ? $errorCode : '-'); ?></p>
</div>
<div>
<small><?php e(t('IP')); ?></small>
<p><?php e($ip !== '' ? $ip : '-'); ?></p>
</div>
</div>
<?php endif; ?>
<?php if ($userAgent !== ''): ?>
<div>
<small><?php e(t('User agent')); ?></small>
<textarea readonly rows="3"><?php e($userAgent); ?></textarea>
</div>
<?php endif; ?>
</details>
<hr>
<details open>
<summary><?php e(t('Scope')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('User')); ?></small>
<p>
<?php if (!empty($auditLog['user_uuid'])): ?>
<a href="admin/users/edit/<?php e($auditLog['user_uuid']); ?>"><?php e($userLabel); ?></a>
<?php else: ?>
<?php e($userLabel); ?>
<?php endif; ?>
</p>
</div>
<div>
<small><?php e(t('Tenant')); ?></small>
<p>
<?php if (!empty($auditLog['tenant_uuid'])): ?>
<a href="admin/tenants/edit/<?php e($auditLog['tenant_uuid']); ?>"><?php e($tenantLabel); ?></a>
<?php else: ?>
<?php e($tenantLabel); ?>
<?php endif; ?>
</p>
</div>
</div>
<?php if ($tokenId > 0 || $tokenTenantId > 0): ?>
<div class="grid">
<div>
<small><?php e(t('Token ID')); ?></small>
<p><?php e($tokenId > 0 ? (string) $tokenId : '-'); ?></p>
</div>
<div>
<small><?php e(t('Token tenant')); ?></small>
<p><?php e($tokenTenantId > 0 ? (string) $tokenTenantId : '-'); ?></p>
</div>
</div>
<?php endif; ?>
</details>
<?php if ($queryPretty !== '-'): ?>
<hr>
<details>
<summary><?php e(t('Query')); ?></summary>
<hr>
<textarea readonly rows="12"><?php e($queryPretty); ?></textarea>
</details>
<?php endif; ?>
</div>
</section>
<aside id="app-details-aside-section">
<div class="app-details-aside-section">
<hgroup>
<strong><?php e(t('API audit')); ?></strong>
<p><small><?php e($requestId !== '' ? $requestId : '-'); ?></small></p>
</hgroup>
<hr>
<div class="grid">
<div>
<small><?php e(t('ID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditLog['id'] ?? '')); ?>">
<?php e((string) ($auditLog['id'] ?? '-')); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('Status')); ?></small>
<p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e((string) $statusCode); ?></span></p>
</div>
</div>
<div>
<small><?php e(t('Request ID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e($requestId); ?>">
<?php e($requestId !== '' ? substr($requestId, 0, 10) : '-'); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('Created')); ?></small>
<p><?php e(dt((string) ($auditLog['created_at'] ?? '')) ?: '-'); ?></p>
</div>
<div>
<small><?php e(t('Duration (ms)')); ?></small>
<p><?php e($durationMs > 0 ? (string) $durationMs : '-'); ?></p>
</div>
</div>
</aside>
</div>

View File

@@ -1,107 +0,0 @@
<?php
use MintyPHP\Http\RequestContext;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Audit\FrontendTelemetryIngestService;
use MintyPHP\Session;
if ((requestInput()->method()) !== 'POST') {
http_response_code(405);
Router::json(['ok' => false, 'error' => 'method_not_allowed']);
return;
}
$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$currentUserId = (int) ($session['user']['id'] ?? 0);
if ($currentUserId <= 0) {
http_response_code(403);
Router::json(['ok' => false, 'error' => 'forbidden']);
return;
}
if (!Session::checkCsrfToken()) {
http_response_code(403);
Router::json(['ok' => false, 'error' => 'csrf']);
return;
}
$body = requestInput()->bodyAll();
if (!is_array($body)) {
http_response_code(204);
return;
}
$allowedKeys = ['event_type', 'severity', 'message', 'fingerprint', 'meta', 'occurred_at'];
$csrfKey = Session::$csrfSessionKey;
foreach ($body as $key => $value) {
if (!is_string($key)) {
continue;
}
if ($key === $csrfKey) {
continue;
}
if (!in_array($key, $allowedKeys, true)) {
http_response_code(204);
return;
}
}
$payload = [];
foreach ($allowedKeys as $key) {
if (!array_key_exists($key, $body)) {
continue;
}
$payload[$key] = $body[$key];
}
$eventType = $payload['event_type'] ?? null;
$severity = $payload['severity'] ?? null;
$message = $payload['message'] ?? null;
$fingerprint = $payload['fingerprint'] ?? null;
$meta = $payload['meta'] ?? null;
$occurredAt = $payload['occurred_at'] ?? null;
if (($eventType !== null && is_array($eventType))
|| ($severity !== null && is_array($severity))
|| ($message !== null && is_array($message))
|| ($fingerprint !== null && is_array($fingerprint))
|| ($occurredAt !== null && is_array($occurredAt))
|| ($meta !== null && !is_array($meta) && !is_string($meta))
) {
http_response_code(204);
return;
}
$eventTypeLength = strlen((string) $eventType);
$severityLength = strlen((string) $severity);
$messageLength = strlen((string) $message);
$fingerprintLength = strlen((string) $fingerprint);
$occurredAtLength = strlen((string) $occurredAt);
$metaLength = is_string($meta) ? strlen($meta) : 0;
if ($eventTypeLength > 64
|| $severityLength > 16
|| $messageLength > 1000
|| $fingerprintLength > 256
|| $occurredAtLength > 64
|| $metaLength > 2048
) {
http_response_code(204);
return;
}
$payloadSize = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (is_string($payloadSize) && strlen($payloadSize) > 4096) {
http_response_code(204);
return;
}
$result = app(FrontendTelemetryIngestService::class)->ingest($payload);
if (!(bool) ($result['accepted'] ?? false) && (string) ($result['reason'] ?? '') === 'record_failed') {
error_log('[frontend-telemetry] ingest record_failed request_id=' . RequestContext::id());
}
http_response_code(204);

View File

@@ -1,45 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\ImportAuditStatus;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\ImportAuditService;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_AUDIT_VIEW);
gridRequireGetRequest();
$importAuditService = app(ImportAuditService::class);
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$result = $importAuditService->listPaged($filters);
$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
$status = ImportAuditStatus::normalizeOr((string) ($row['status'] ?? ''), ImportAuditStatus::Failed);
$userLabel = trim((string) ($row['user_display_name'] ?? ''));
$userEmail = trim((string) ($row['user_email'] ?? ''));
if ($userLabel === '') {
$userLabel = $userEmail !== '' ? $userEmail : '-';
}
$rows[] = [
'id' => (int) ($row['id'] ?? 0),
'started_at' => dt((string) ($row['started_at'] ?? '')),
'profile_key' => (string) ($row['profile_key'] ?? ''),
'status' => $status->value,
'status_badge' => $status->badgeVariant(),
'status_label' => t($status->labelToken()),
'duration_ms' => (int) ($row['duration_ms'] ?? 0),
'rows_total' => (int) ($row['rows_total'] ?? 0),
'created_count' => (int) ($row['created_count'] ?? 0),
'skipped_count' => (int) ($row['skipped_count'] ?? 0),
'failed_count' => (int) ($row['failed_count'] ?? 0),
'user_uuid' => (string) ($row['user_uuid'] ?? ''),
'user_label' => $userLabel,
];
}
gridJsonDataResult($rows, (int) ($result['total'] ?? 0));

View File

@@ -1,82 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\ImportAuditStatus;
$importAuditStatusItems = array_map(
static fn (ImportAuditStatus $status): array => [
'id' => $status->value,
'description' => $status->labelToken(),
],
ImportAuditStatus::cases()
);
return gridFilterSchema([
'query' => [
'limit' => ['type' => 'int', 'default' => 20, 'min' => 1, 'max' => 200],
'offset' => ['type' => 'int', 'default' => 0, 'min' => 0],
'search' => ['type' => 'string'],
'profile_key' => ['type' => 'enum', 'allowed' => ['users', 'departments'], 'default' => '', 'lowercase' => true],
'status' => ['type' => 'enum', 'allowed' => ImportAuditStatus::values(), 'default' => '', 'lowercase' => true],
'created_from' => ['type' => 'date'],
'created_to' => ['type' => 'date'],
'user_ids' => ['type' => 'csv_ids', 'max' => 200],
'order' => ['type' => 'order', 'allowed' => ['started_at', 'status', 'profile_key', 'duration_ms', 'rows_total', 'created_count', 'skipped_count', 'failed_count'], 'default' => 'started_at'],
'dir' => ['type' => 'dir', 'default' => 'desc'],
],
'toolbar' => [
[
'key' => 'search',
'type' => 'text',
'label' => 'Search',
'placeholder' => 'Search...',
'input_id' => 'import-audit-search',
'search' => true,
'query' => ['type' => 'string'],
],
[
'key' => 'profile_key',
'type' => 'select',
'label' => 'Profile',
'input_id' => 'import-audit-profile-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All profiles'],
['id' => 'users', 'description' => 'Users'],
['id' => 'departments', 'description' => 'Departments'],
],
],
[
'key' => 'status',
'type' => 'select',
'label' => 'Status',
'input_id' => 'import-audit-status-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All statuses'],
...$importAuditStatusItems,
],
],
[
'key' => 'created_from',
'type' => 'date',
'label' => 'Created from',
'input_id' => 'import-audit-created-from',
],
[
'key' => 'created_to',
'type' => 'date',
'label' => 'Created to',
'input_id' => 'import-audit-created-to',
],
[
'key' => 'user_ids',
'type' => 'multi_csv',
'label' => 'Users',
'placeholder' => 'Select users',
'input_id' => 'import-audit-user-ids-filter',
'options_key' => 'user_items',
'default' => [],
'query' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
],
],
]);

View File

@@ -1,15 +0,0 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Support\Guard;
Guard::requireLogin();
$slug = trim((string) ($slug ?? ''));
if ($slug === '') {
require __DIR__ . '/index().php';
return;
}
Router::redirect('error/not_found?url=' . urlencode(Request::pathWithQuery()));

View File

@@ -1,118 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\ImportAuditService;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_AUDIT_PURGE
);
Buffer::set('title', t('Import audit logs'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
...gridSchemaQuery($filterSchema),
'user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(ImportAuditService::class)->filterOptions(200);
$activeUserIds = array_map('strval', is_array($filterState['user_ids'] ?? null) ? $filterState['user_ids'] : []);
$importAuditUserItems = [];
foreach ((array) ($filterOptions['users'] ?? []) as $userOption) {
if (!is_array($userOption)) {
continue;
}
$userId = (int) ($userOption['id'] ?? 0);
if ($userId <= 0) {
continue;
}
$displayName = trim((string) ($userOption['display_name'] ?? ''));
$email = trim((string) ($userOption['email'] ?? ''));
$exists = (bool) ($userOption['exists'] ?? false);
$label = $displayName !== '' ? $displayName : $email;
if ($label === '') {
$label = $exists
? sprintf(t('User #%d'), $userId)
: sprintf(t('User #%d (deleted)'), $userId);
}
$id = (string) $userId;
$importAuditUserItems[$id] = [
'id' => $id,
'description' => $label,
];
}
foreach ($activeUserIds as $userId) {
if (!isset($importAuditUserItems[$userId])) {
$importAuditUserItems[$userId] = [
'id' => $userId,
'description' => sprintf(t('User #%d (deleted)'), (int) $userId),
];
}
}
$importAuditUserItems = array_values($importAuditUserItems);
$toolbarFilterState = [
'search' => (string) ($filterState['search'] ?? ''),
'profile_key' => (string) ($filterState['profile_key'] ?? ''),
'status' => (string) ($filterState['status'] ?? ''),
'created_from' => (string) ($filterState['created_from'] ?? ''),
'created_to' => (string) ($filterState['created_to'] ?? ''),
'user_ids' => $activeUserIds,
];
$toolbarOptionSets = [
'user_items' => $importAuditUserItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
'filter_state' => $filterState,
'search_keys' => ['search'],
'toolbar_state_overrides' => $toolbarFilterState,
'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
'search' => [
'label' => t('Search'),
'type' => 'text',
],
'profile_key' => [
'label' => t('Profile'),
'type' => 'select',
'default' => (string) (($schemaByKey['profile_key']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['profile_key'] ?? [])),
],
'status' => [
'label' => t('Status'),
'type' => 'select',
'default' => (string) (($schemaByKey['status']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
],
'user_ids' => [
'label' => t('Users'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($importAuditUserItems),
],
'created_range' => [
'label' => t('Created'),
'type' => 'date_range',
'from_param' => 'created_from',
'to_param' => 'created_to',
],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];

View File

@@ -1,72 +0,0 @@
<?php
$pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canPurgeImportAudit = (bool) ($pageAuth['can_purge'] ?? false);
$toolbarFilterSchema = is_array($toolbarFilterSchema ?? null) ? $toolbarFilterSchema : [];
$searchToolbarFilterSchema = is_array($searchToolbarFilterSchema ?? null) ? $searchToolbarFilterSchema : [];
$drawerToolbarFilterSchema = is_array($drawerToolbarFilterSchema ?? null) ? $drawerToolbarFilterSchema : [];
$toolbarFilterState = is_array($toolbarFilterState ?? null) ? $toolbarFilterState : [];
$toolbarOptionSets = is_array($toolbarOptionSets ?? null) ? $toolbarOptionSets : [];
$filterChipMeta = is_array($filterChipMeta ?? null) ? $filterChipMeta : [];
$clientFilterSchema = is_array($clientFilterSchema ?? null) ? $clientFilterSchema : [];
$searchConfig = is_array($searchConfig ?? null) ? $searchConfig : null;
?>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('Import audit logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<?php
$listTitle = t('Import audit logs');
ob_start();
?>
<?php
$listPurgeEnabled = $canPurgeImportAudit;
$listPurgeFormId = 'import-audit-purge-form';
$listPurgeAction = 'admin/import-audit/purge';
$listPurgeConfirmMessage = t('Purge entries older than 90 days?');
$listPurgeButtonLabel = t('Purge import logs');
require templatePath('partials/app-list-purge-action.phtml');
?>
<?php
$listTitleActionsHtml = ob_get_clean();
require templatePath('partials/app-list-titlebar.phtml');
?>
<?php
$filterUiNamespace = 'import-audit';
require templatePath('partials/app-list-filters.phtml');
?>
<div class="app-list-table">
<div id="import-audit-grid"></div>
</div>
<?php
$gridLang = json_decode(appBufferValue('grid_lang'), true);
if (!is_array($gridLang)) {
$gridLang = [];
}
$pageConfig = [
'gridSearch' => $searchConfig,
'filterSchema' => $clientFilterSchema,
'filterChipMeta' => $filterChipMeta,
'gridLang' => $gridLang,
'labels' => [
'created' => t('Created'),
'status' => t('Status'),
'profile' => t('Profile'),
'durationMs' => t('Duration (ms)'),
'rowsTotal' => t('Rows total'),
'createdCount' => t('Created count'),
'skippedCount' => t('Skipped count'),
'failedCount' => t('Failed count'),
'user' => t('User'),
'users' => t('Users'),
'departments' => t('Departments'),
],
];
?>
<script src="<?php e(assetVersion('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="application/json" id="page-config-admin-import-audit-index"><?php gridJsonForJs($pageConfig); ?></script>
<script type="module" src="<?php e(assetVersion('js/pages/admin-import-audit-index.js')); ?>"></script>

View File

@@ -1,24 +0,0 @@
<?php
use MintyPHP\Router;
use MintyPHP\Service\Audit\ImportAuditService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE);
if (strtoupper((string) (requestInput()->method())) !== 'POST') {
Router::redirect('admin/import-audit');
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, 'admin/import-audit', 'import_audit');
Router::redirect('admin/import-audit');
}
$deleted = app(ImportAuditService::class)->purgeExpired();
Flash::success(sprintf(t('%d import audit entries purged'), $deleted), 'admin/import-audit', 'import_audit_purged');
Router::redirect('admin/import-audit');

View File

@@ -1,18 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_AUDIT_VIEW);
$runId = (int) ($id ?? 0);
$auditRun = $runId > 0 ? app(\MintyPHP\Service\Audit\ImportAuditService::class)->find($runId) : null;
if (!$auditRun) {
Flash::error(t('Import audit entry not found'), 'admin/import-audit', 'import_audit_not_found');
Router::redirect('admin/import-audit');
}
Buffer::set('title', t('View import audit entry'));

View File

@@ -1,238 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\ImportAuditStatus;
/**
* @var array $auditRun
*/
$auditRun = $auditRun ?? [];
$status = ImportAuditStatus::normalizeOr((string) ($auditRun['status'] ?? ''), ImportAuditStatus::Failed);
$statusVariant = $status->badgeVariant();
$profileKey = strtolower(trim((string) ($auditRun['profile_key'] ?? '')));
$profileLabel = $profileKey;
if ($profileKey === 'users') {
$profileLabel = t('Users');
} elseif ($profileKey === 'departments') {
$profileLabel = t('Departments');
}
$mappedCsv = trim((string) ($auditRun['mapped_targets_csv'] ?? ''));
$mappedFields = [];
if ($mappedCsv !== '') {
$mappedFields = array_values(array_filter(array_map('trim', explode(',', $mappedCsv)), static fn ($item) => $item !== ''));
}
$errorCodesJson = trim((string) ($auditRun['error_codes_json'] ?? ''));
$errorCodes = [];
if ($errorCodesJson !== '') {
$decoded = json_decode($errorCodesJson, true);
if (is_array($decoded)) {
foreach ($decoded as $code => $count) {
$code = trim((string) $code);
$count = (int) $count;
if ($code === '' || $count <= 0) {
continue;
}
$errorCodes[$code] = $count;
}
}
}
arsort($errorCodes);
$userLabel = trim((string) ($auditRun['user_display_name'] ?? ''));
$userEmail = trim((string) ($auditRun['user_email'] ?? ''));
if ($userLabel === '') {
$userLabel = $userEmail !== '' ? $userEmail : '-';
}
$tenantLabel = trim((string) ($auditRun['current_tenant_description'] ?? ''));
if ($tenantLabel === '') {
$tenantLabel = '-';
}
?>
<div class="app-details-container">
<section>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('Import audit logs'), 'path' => 'admin/import-audit'],
['label' => t('View')],
];
require templatePath('partials/app-breadcrumb.phtml');
$titlebar = [
'title' => t('View import audit entry'),
'backHref' => 'admin/import-audit',
'backTitle' => t('Back'),
];
require templatePath('partials/app-details-titlebar.phtml');
?>
<div class="app-details-content">
<details open>
<summary><?php e(t('Import details')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Profile')); ?></small>
<p><span class="badge" data-variant="neutral"><?php e($profileLabel !== '' ? $profileLabel : '-'); ?></span></p>
</div>
<div>
<small><?php e(t('Status')); ?></small>
<p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Started')); ?></small>
<p><?php e(dt((string) ($auditRun['started_at'] ?? '')) ?: '-'); ?></p>
</div>
<div>
<small><?php e(t('Finished')); ?></small>
<p><?php e(dt((string) ($auditRun['finished_at'] ?? '')) ?: '-'); ?></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Duration (ms)')); ?></small>
<p><?php e((int) ($auditRun['duration_ms'] ?? 0) > 0 ? (string) ((int) $auditRun['duration_ms']) : '-'); ?></p>
</div>
<div>
<small><?php e(t('File')); ?></small>
<p><?php e((string) ($auditRun['source_filename'] ?? '') !== '' ? (string) $auditRun['source_filename'] : '-'); ?></p>
</div>
</div>
</details>
<hr>
<details open>
<summary><?php e(t('Counters')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Rows total')); ?></small>
<p><?php e((string) ((int) ($auditRun['rows_total'] ?? 0))); ?></p>
</div>
<div>
<small><?php e(t('Created count')); ?></small>
<p><?php e((string) ((int) ($auditRun['created_count'] ?? 0))); ?></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Skipped count')); ?></small>
<p><?php e((string) ((int) ($auditRun['skipped_count'] ?? 0))); ?></p>
</div>
<div>
<small><?php e(t('Failed count')); ?></small>
<p><?php e((string) ((int) ($auditRun['failed_count'] ?? 0))); ?></p>
</div>
</div>
</details>
<hr>
<details open>
<summary><?php e(t('Scope')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('User')); ?></small>
<p>
<?php if (!empty($auditRun['user_uuid'])): ?>
<a href="admin/users/edit/<?php e((string) $auditRun['user_uuid']); ?>"><?php e($userLabel); ?></a>
<?php else: ?>
<?php e($userLabel); ?>
<?php endif; ?>
</p>
</div>
<div>
<small><?php e(t('Current tenant')); ?></small>
<p>
<?php if (!empty($auditRun['current_tenant_uuid'])): ?>
<a href="admin/tenants/edit/<?php e((string) $auditRun['current_tenant_uuid']); ?>"><?php e($tenantLabel); ?></a>
<?php else: ?>
<?php e($tenantLabel); ?>
<?php endif; ?>
</p>
</div>
</div>
</details>
<?php if ($mappedFields): ?>
<hr>
<details>
<summary><?php e(t('Mapped fields')); ?></summary>
<hr>
<p><?php e(implode(', ', $mappedFields)); ?></p>
</details>
<?php endif; ?>
<?php if ($errorCodes): ?>
<hr>
<details>
<summary><?php e(t('Error code distribution')); ?></summary>
<hr>
<div class="app-list-table">
<table>
<thead>
<tr>
<th><?php e(t('Error code')); ?></th>
<th><?php e(t('Count')); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($errorCodes as $code => $count): ?>
<tr>
<td><code><?php e((string) $code); ?></code></td>
<td><?php e((string) $count); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</details>
<?php endif; ?>
</div>
</section>
<aside id="app-details-aside-section">
<div class="app-details-aside-section">
<hgroup>
<strong><?php e(t('Import logs')); ?></strong>
<p><small><?php e((string) ($auditRun['run_uuid'] ?? '') !== '' ? (string) $auditRun['run_uuid'] : '-'); ?></small></p>
</hgroup>
<hr>
<div class="grid">
<div>
<small><?php e(t('ID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditRun['id'] ?? '')); ?>">
<?php e((string) ($auditRun['id'] ?? '-')); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('Status')); ?></small>
<p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
</div>
</div>
<div>
<small><?php e(t('Run UUID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditRun['run_uuid'] ?? '')); ?>">
<?php e((string) ($auditRun['run_uuid'] ?? '') !== '' ? substr((string) $auditRun['run_uuid'], 0, 10) : '-'); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('Created')); ?></small>
<p><?php e(dt((string) ($auditRun['started_at'] ?? '')) ?: '-'); ?></p>
</div>
<div>
<small><?php e(t('Duration (ms)')); ?></small>
<p><?php e((int) ($auditRun['duration_ms'] ?? 0) > 0 ? (string) ((int) $auditRun['duration_ms']) : '-'); ?></p>
</div>
</div>
</aside>
</div>

View File

@@ -11,7 +11,7 @@ Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_AUDIT_PURGE
UiCapabilityMap::PAGE_JOBS_PURGE
);
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), gridSchemaQuery($filterSchema));

View File

@@ -99,9 +99,9 @@ $pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canViewMailLog = (bool) ($pageAuth['can_view_mail_log'] ?? false);
$canViewUsers = (bool) ($pageAuth['can_view_users'] ?? false);
$canViewTenants = (bool) ($pageAuth['can_view_tenants'] ?? false);
$canViewImportAudit = (bool) ($pageAuth['can_view_imports_audit'] ?? false);
$canViewSystemAudit = (bool) ($pageAuth['can_view_system_audit'] ?? false);
$canViewUserLifecycleAudit = (bool) ($pageAuth['can_view_user_lifecycle_audit'] ?? false);
$canViewImportAudit = false;
$canViewSystemAudit = false;
$canViewUserLifecycleAudit = false;
$canViewAuditTab = (bool) ($auditStatsAvailable ?? false) && (
($canViewSystemAudit && (bool) ($systemAuditStatsAvailable ?? false))
|| ($canViewUserLifecycleAudit && (bool) ($userLifecycleAuditStatsAvailable ?? false))

View File

@@ -1,45 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\SystemAuditChannel;
use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_VIEW);
gridRequireGetRequest();
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$result = app(SystemAuditService::class)->listPaged($filters);
$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
$outcome = SystemAuditOutcome::normalizeOr((string) ($row['outcome'] ?? ''), SystemAuditOutcome::Success);
$channel = SystemAuditChannel::normalizeOr((string) ($row['channel'] ?? ''), SystemAuditChannel::Web);
$actorLabel = trim((string) ($row['actor_user_display_name'] ?? ''));
if ($actorLabel === '') {
$actorLabel = trim((string) ($row['actor_user_email'] ?? ''));
}
$rows[] = [
'id' => (int) ($row['id'] ?? 0),
'created_at' => dt((string) ($row['created_at'] ?? '')),
'event_type' => (string) ($row['event_type'] ?? ''),
'outcome' => $outcome->value,
'outcome_badge' => $outcome->badgeVariant(),
'outcome_label' => t($outcome->labelToken()),
'channel' => strtoupper($channel->labelToken()),
'actor_user_id' => (int) ($row['actor_user_id'] ?? 0),
'actor_user_uuid' => (string) ($row['actor_user_uuid'] ?? ''),
'actor_user_label' => $actorLabel !== '' ? $actorLabel : '-',
'target_type' => (string) ($row['target_type'] ?? ''),
'target_uuid' => (string) ($row['target_uuid'] ?? ''),
'request_id' => (string) ($row['request_id'] ?? ''),
'error_code' => (string) ($row['error_code'] ?? ''),
];
}
gridJsonDataResult($rows, (int) ($result['total'] ?? 0));

View File

@@ -1,121 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\SystemAuditChannel;
use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
$outcomeItems = array_map(
static fn (SystemAuditOutcome $outcome): array => [
'id' => $outcome->value,
'description' => $outcome->labelToken(),
],
SystemAuditOutcome::cases()
);
$channelItems = array_map(
static fn (SystemAuditChannel $channel): array => [
'id' => $channel->value,
'description' => $channel->labelToken(),
'translate' => false,
],
SystemAuditChannel::cases()
);
return gridFilterSchema([
'query' => [
'limit' => ['type' => 'int', 'default' => 20, 'min' => 1, 'max' => 200],
'offset' => ['type' => 'int', 'default' => 0, 'min' => 0],
'search' => ['type' => 'string'],
'event_types' => [
'type' => 'csv_strings',
'max' => 200,
'sanitizer' => static function (string $value): string {
$value = strtolower(trim($value));
if ($value === '' || strlen($value) > 64) {
return '';
}
return preg_match('/^[a-z0-9._-]+$/', $value) === 1 ? $value : '';
},
],
'outcome' => ['type' => 'enum', 'allowed' => SystemAuditOutcome::values(), 'default' => '', 'lowercase' => true],
'channel' => ['type' => 'enum', 'allowed' => SystemAuditChannel::values(), 'default' => '', 'lowercase' => true],
'created_from' => ['type' => 'date'],
'created_to' => ['type' => 'date'],
'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200],
'target_type' => ['type' => 'string'],
'request_id' => ['type' => 'string'],
'order' => ['type' => 'order', 'allowed' => ['id', 'created_at', 'event_type', 'outcome', 'channel', 'actor_user_id'], 'default' => 'created_at'],
'dir' => ['type' => 'dir', 'default' => 'desc'],
],
'toolbar' => [
[
'key' => 'search',
'type' => 'text',
'label' => 'Search',
'placeholder' => 'Search...',
'input_id' => 'system-audit-search',
'search' => true,
'query' => ['type' => 'string'],
],
[
'key' => 'outcome',
'type' => 'select',
'label' => 'Status',
'input_id' => 'system-audit-outcome-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All outcomes'],
...$outcomeItems,
],
],
[
'key' => 'channel',
'type' => 'select',
'label' => 'Channel',
'input_id' => 'system-audit-channel-filter',
'default' => '',
'allowed' => [
['id' => '', 'description' => 'All channels'],
...$channelItems,
],
],
[
'key' => 'event_types',
'type' => 'multi_csv',
'label' => 'Event type',
'placeholder' => 'Select event types',
'input_id' => 'system-audit-event-types-filter',
'options_key' => 'event_type_items',
'default' => [],
'query' => ['type' => 'csv_strings', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'created_from',
'type' => 'date',
'label' => 'Created from',
'input_id' => 'system-audit-created-from',
],
[
'key' => 'created_to',
'type' => 'date',
'label' => 'Created to',
'input_id' => 'system-audit-created-to',
],
[
'key' => 'actor_user_ids',
'type' => 'multi_csv',
'label' => 'Actor',
'placeholder' => 'Select actor users',
'input_id' => 'system-audit-actor-users-filter',
'options_key' => 'actor_user_items',
'default' => [],
'query' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'request_id',
'type' => 'text',
'label' => 'Request ID',
'input_id' => 'system-audit-request-id',
'normalize' => 'trim_lower',
'event' => 'input',
],
],
]);

View File

@@ -1,15 +0,0 @@
<?php
use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Support\Guard;
Guard::requireLogin();
$slug = trim((string) ($slug ?? ''));
if ($slug === '') {
require __DIR__ . '/index().php';
return;
}
Router::redirect('error/not_found?url=' . urlencode(Request::pathWithQuery()));

View File

@@ -1,170 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_SYSTEM_AUDIT
);
Buffer::set('title', t('System audit logs'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
...gridSchemaQuery($filterSchema),
'event_types' => [
'type' => 'csv_strings',
'max' => 200,
'return' => 'array',
'sanitizer' => static function (string $value): string {
$value = strtolower(trim($value));
if ($value === '' || strlen($value) > 64) {
return '';
}
return preg_match('/^[a-z0-9._-]+$/', $value) === 1 ? $value : '';
},
],
'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(SystemAuditService::class)->filterOptions(200);
$activeEventTypes = is_array($filterState['event_types'] ?? null) ? $filterState['event_types'] : [];
$activeActorUserIds = array_map('strval', is_array($filterState['actor_user_ids'] ?? null) ? $filterState['actor_user_ids'] : []);
$eventTypeItems = [];
foreach ((array) ($filterOptions['event_types'] ?? []) as $eventType) {
$eventType = strtolower(trim((string) $eventType));
if ($eventType === '') {
continue;
}
$eventTypeItems[$eventType] = [
'id' => $eventType,
'description' => $eventType,
];
}
foreach ($activeEventTypes as $eventType) {
if (!isset($eventTypeItems[$eventType])) {
$eventTypeItems[$eventType] = [
'id' => $eventType,
'description' => $eventType,
];
}
}
$eventTypeItems = array_values($eventTypeItems);
$actorUserItems = [];
foreach ((array) ($filterOptions['actors'] ?? []) as $actorOption) {
if (!is_array($actorOption)) {
continue;
}
$actorId = (int) ($actorOption['id'] ?? 0);
if ($actorId <= 0) {
continue;
}
$actorDisplayName = trim((string) ($actorOption['display_name'] ?? ''));
$actorEmail = trim((string) ($actorOption['email'] ?? ''));
$actorExists = (bool) ($actorOption['exists'] ?? false);
$label = $actorDisplayName !== '' ? $actorDisplayName : $actorEmail;
if ($label === '') {
$label = $actorExists
? sprintf(t('User #%d'), $actorId)
: sprintf(t('User #%d (deleted)'), $actorId);
}
$id = (string) $actorId;
$actorUserItems[$id] = [
'id' => $id,
'description' => $label,
];
}
foreach ($activeActorUserIds as $actorId) {
if (!isset($actorUserItems[$actorId])) {
$actorUserItems[$actorId] = [
'id' => $actorId,
'description' => sprintf(t('User #%d (deleted)'), (int) $actorId),
];
}
}
$actorUserItems = array_values($actorUserItems);
$toolbarFilterState = [
'search' => (string) ($filterState['search'] ?? ''),
'event_types' => $activeEventTypes,
'outcome' => (string) ($filterState['outcome'] ?? ''),
'channel' => (string) ($filterState['channel'] ?? ''),
'created_from' => (string) ($filterState['created_from'] ?? ''),
'created_to' => (string) ($filterState['created_to'] ?? ''),
'actor_user_ids' => $activeActorUserIds,
'request_id' => (string) ($filterState['request_id'] ?? ''),
];
$toolbarOptionSets = [
'event_type_items' => $eventTypeItems,
'actor_user_items' => $actorUserItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
'filter_state' => $filterState,
'search_keys' => ['search'],
'toolbar_state_overrides' => $toolbarFilterState,
'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
'search' => [
'label' => t('Search'),
'type' => 'text',
],
'outcome' => [
'label' => t('Status'),
'type' => 'select',
'default' => (string) (($schemaByKey['outcome']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['outcome'] ?? [])),
],
'channel' => [
'label' => t('Channel'),
'type' => 'select',
'default' => (string) (($schemaByKey['channel']['default'] ?? '')),
'options' => gridOptionMapFromAllowed((array) ($schemaByKey['channel'] ?? [])),
],
'event_types' => [
'label' => t('Event type'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($eventTypeItems),
],
'actor_user_ids' => [
'label' => t('Actor'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($actorUserItems),
],
'request_id' => [
'label' => t('Request ID'),
'type' => 'text',
],
'created_range' => [
'label' => t('Created'),
'type' => 'date_range',
'from_param' => 'created_from',
'to_param' => 'created_to',
],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];

View File

@@ -1,69 +0,0 @@
<?php
$pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canPurgeSystemAudit = (bool) ($pageAuth['can_purge_system_audit'] ?? false);
$toolbarFilterSchema = is_array($toolbarFilterSchema ?? null) ? $toolbarFilterSchema : [];
$searchToolbarFilterSchema = is_array($searchToolbarFilterSchema ?? null) ? $searchToolbarFilterSchema : [];
$drawerToolbarFilterSchema = is_array($drawerToolbarFilterSchema ?? null) ? $drawerToolbarFilterSchema : [];
$toolbarFilterState = is_array($toolbarFilterState ?? null) ? $toolbarFilterState : [];
$toolbarOptionSets = is_array($toolbarOptionSets ?? null) ? $toolbarOptionSets : [];
$filterChipMeta = is_array($filterChipMeta ?? null) ? $filterChipMeta : [];
$clientFilterSchema = is_array($clientFilterSchema ?? null) ? $clientFilterSchema : [];
$searchConfig = is_array($searchConfig ?? null) ? $searchConfig : null;
?>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('System audit logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<?php
$listTitle = t('System audit logs');
ob_start();
?>
<?php
$listPurgeEnabled = $canPurgeSystemAudit;
$listPurgeFormId = 'system-audit-purge-form';
$listPurgeAction = 'admin/system-audit/purge';
$listPurgeConfirmMessage = t('Purge expired system audit entries?');
$listPurgeButtonLabel = t('Purge system audit logs');
require templatePath('partials/app-list-purge-action.phtml');
?>
<?php
$listTitleActionsHtml = ob_get_clean();
require templatePath('partials/app-list-titlebar.phtml');
?>
<?php
$filterUiNamespace = 'system-audit';
require templatePath('partials/app-list-filters.phtml');
?>
<div class="app-list-table">
<div id="system-audit-grid"></div>
</div>
<?php
$gridLang = json_decode(appBufferValue('grid_lang'), true);
if (!is_array($gridLang)) {
$gridLang = [];
}
$pageConfig = [
'gridSearch' => $searchConfig,
'filterSchema' => $clientFilterSchema,
'filterChipMeta' => $filterChipMeta,
'gridLang' => $gridLang,
'labels' => [
'created' => t('Created'),
'status' => t('Status'),
'event' => t('Event'),
'channel' => t('Channel'),
'actor' => t('Actor'),
'targetType' => t('Target type'),
'requestId' => t('Request ID'),
'errorCode' => t('Error code'),
],
];
?>
<script src="<?php e(assetVersion('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="application/json" id="page-config-admin-system-audit-index"><?php gridJsonForJs($pageConfig); ?></script>
<script type="module" src="<?php e(assetVersion('js/pages/admin-system-audit-index.js')); ?>"></script>

View File

@@ -1,32 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
use MintyPHP\Router;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_PURGE);
if (strtoupper((string) requestInput()->method()) !== 'POST') {
Router::redirect('admin/system-audit');
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, 'admin/system-audit', 'system_audit');
Router::redirect('admin/system-audit');
}
$service = app(SystemAuditService::class);
$deleted = $service->purgeExpired();
$service->record('admin.system_audit.purge', SystemAuditOutcome::Success->value, [
'metadata' => ['deleted_count' => $deleted],
]);
Flash::success(sprintf(t('%d system audit entries purged'), $deleted), 'admin/system-audit', 'system_audit_purged');
Router::redirect('admin/system-audit');

View File

@@ -1,20 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_VIEW);
$auditId = (int) ($id ?? 0);
$auditLog = $auditId > 0 ? app(SystemAuditService::class)->find($auditId) : null;
if (!$auditLog) {
Flash::error(t('System audit entry not found'), 'admin/system-audit', 'system_audit_not_found');
Router::redirect('admin/system-audit');
}
Buffer::set('title', t('View system audit entry'));

View File

@@ -1,191 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
/**
* @var array $auditLog
*/
$auditLog = $auditLog ?? [];
$outcome = SystemAuditOutcome::normalizeOr((string) ($auditLog['outcome'] ?? ''), SystemAuditOutcome::Success);
$outcomeVariant = $outcome->badgeVariant();
$metadataJson = trim((string) ($auditLog['metadata_json'] ?? ''));
$metadataPretty = '-';
if ($metadataJson !== '') {
$decoded = json_decode($metadataJson, true);
if (is_array($decoded)) {
$pretty = json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$metadataPretty = is_string($pretty) ? $pretty : $metadataJson;
} else {
$metadataPretty = $metadataJson;
}
}
$requestId = trim((string) ($auditLog['request_id'] ?? ''));
$eventType = trim((string) ($auditLog['event_type'] ?? ''));
$channel = strtoupper(trim((string) ($auditLog['channel'] ?? '')));
$errorCode = trim((string) ($auditLog['error_code'] ?? ''));
$method = strtoupper(trim((string) ($auditLog['method'] ?? '')));
$path = trim((string) ($auditLog['path'] ?? ''));
$targetType = trim((string) ($auditLog['target_type'] ?? ''));
$targetUuid = trim((string) ($auditLog['target_uuid'] ?? ''));
$ipHash = trim((string) ($auditLog['ip_hash'] ?? ''));
$userAgentHash = trim((string) ($auditLog['user_agent_hash'] ?? ''));
$actorLabel = trim((string) ($auditLog['actor_user_display_name'] ?? ''));
$actorEmail = trim((string) ($auditLog['actor_user_email'] ?? ''));
if ($actorLabel === '') {
$actorLabel = $actorEmail !== '' ? $actorEmail : '-';
}
$tenantLabel = trim((string) ($auditLog['actor_tenant_description'] ?? ''));
if ($tenantLabel === '') {
$tenantLabel = '-';
}
?>
<div class="app-details-container">
<section>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('System audit logs'), 'path' => 'admin/system-audit'],
['label' => t('View')],
];
require templatePath('partials/app-breadcrumb.phtml');
$titlebar = [
'title' => t('View system audit entry'),
'backHref' => 'admin/system-audit',
'backTitle' => t('Back'),
];
require templatePath('partials/app-details-titlebar.phtml');
?>
<div class="app-details-content">
<details open>
<summary><?php e(t('Event details')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Event type')); ?></small>
<p><code><?php e($eventType !== '' ? $eventType : '-'); ?></code></p>
</div>
<div>
<small><?php e(t('Outcome')); ?></small>
<p><span class="badge" data-variant="<?php e($outcomeVariant); ?>"><?php e(t($outcome->labelToken())); ?></span></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Channel')); ?></small>
<p><?php e($channel !== '' ? $channel : '-'); ?></p>
</div>
<div>
<small><?php e(t('Error code')); ?></small>
<p><?php e($errorCode !== '' ? $errorCode : '-'); ?></p>
</div>
</div>
<?php if ($method !== '' || $path !== ''): ?>
<div class="grid">
<div>
<small><?php e(t('Method')); ?></small>
<p><?php e($method !== '' ? $method : '-'); ?></p>
</div>
<div>
<small><?php e(t('Path')); ?></small>
<p><code><?php e($path !== '' ? $path : '-'); ?></code></p>
</div>
</div>
<?php endif; ?>
</details>
<hr>
<details>
<summary><?php e(t('Scope')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Actor')); ?></small>
<p>
<?php if (!empty($auditLog['actor_user_uuid'])): ?>
<a href="admin/users/edit/<?php e($auditLog['actor_user_uuid']); ?>"><?php e($actorLabel); ?></a>
<?php else: ?>
<?php e($actorLabel); ?>
<?php endif; ?>
</p>
</div>
<div>
<small><?php e(t('Actor tenant')); ?></small>
<p>
<?php if (!empty($auditLog['actor_tenant_uuid'])): ?>
<a href="admin/tenants/edit/<?php e($auditLog['actor_tenant_uuid']); ?>"><?php e($tenantLabel); ?></a>
<?php else: ?>
<?php e($tenantLabel); ?>
<?php endif; ?>
</p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Target type')); ?></small>
<p><?php e($targetType !== '' ? $targetType : '-'); ?></p>
</div>
<div>
<small><?php e(t('Target UUID')); ?></small>
<p><code><?php e($targetUuid !== '' ? $targetUuid : '-'); ?></code></p>
</div>
</div>
</details>
<?php if ($metadataPretty !== '-'): ?>
<hr>
<details>
<summary><?php e(t('Metadata')); ?></summary>
<hr>
<textarea readonly rows="14"><?php e($metadataPretty); ?></textarea>
</details>
<?php endif; ?>
</div>
</section>
<aside id="app-details-aside-section">
<div class="app-details-aside-section">
<hgroup>
<strong><?php e(t('System audit')); ?></strong>
<p><small><?php e($requestId !== '' ? $requestId : '-'); ?></small></p>
</hgroup>
<hr>
<div class="grid">
<div>
<small><?php e(t('ID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e((string) ($auditLog['id'] ?? '')); ?>">
<?php e((string) ($auditLog['id'] ?? '-')); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('Created')); ?></small>
<p><?php e(dt((string) ($auditLog['created_at'] ?? '')) ?: '-'); ?></p>
</div>
</div>
<div>
<small><?php e(t('Request ID')); ?></small>
<p>
<span class="badge" data-variant="neutral" data-copy="true" data-copy-value="<?php e($requestId); ?>">
<?php e($requestId !== '' ? substr($requestId, 0, 10) : '-'); ?>
</span>
</p>
</div>
<div>
<small><?php e(t('IP hash')); ?></small>
<p><code><?php e($ipHash !== '' ? substr($ipHash, 0, 16) . '...' : '-'); ?></code></p>
</div>
<div>
<small><?php e(t('User agent hash')); ?></small>
<p><code><?php e($userAgentHash !== '' ? substr($userAgentHash, 0, 16) . '...' : '-'); ?></code></p>
</div>
</div>
</aside>
</div>

View File

@@ -1,40 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW);
gridRequireGetRequest();
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$result = app(\MintyPHP\Service\Audit\UserLifecycleAuditService::class)->listPaged($filters);
$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
$status = UserLifecycleStatus::normalizeOr((string) ($row['status'] ?? ''), UserLifecycleStatus::Failed);
$action = UserLifecycleAction::normalizeOr((string) ($row['action'] ?? ''), UserLifecycleAction::Deactivate);
$triggerType = UserLifecycleTriggerType::normalizeOr((string) ($row['trigger_type'] ?? ''), UserLifecycleTriggerType::System);
$rows[] = [
'id' => (int) ($row['id'] ?? 0),
'created_at' => dt((string) ($row['created_at'] ?? '')),
'status' => $status->value,
'status_badge' => $status->badgeVariant(),
'status_label' => t($status->labelToken()),
'action' => $action->value,
'action_label' => t($action->labelToken()),
'trigger_type' => $triggerType->value,
'trigger_type_label' => t($triggerType->labelToken()),
'reason_code' => (string) ($row['reason_code'] ?? ''),
'target_user_uuid' => (string) ($row['target_user_uuid'] ?? ''),
'target_user_email' => (string) ($row['target_user_email'] ?? ''),
'restored_at' => dt((string) ($row['restored_at'] ?? '')),
];
}
gridJsonDataResult($rows, (int) ($result['total'] ?? 0));

View File

@@ -1,96 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
return gridFilterSchema([
'query' => [
'limit' => ['type' => 'int', 'default' => 20, 'min' => 1, 'max' => 200],
'offset' => ['type' => 'int', 'default' => 0, 'min' => 0],
'search' => ['type' => 'string'],
'actions' => [
'type' => 'csv_strings',
'max' => 200,
'sanitizer' => gridEnumSanitizer(UserLifecycleAction::class),
],
'statuses' => [
'type' => 'csv_strings',
'max' => 200,
'sanitizer' => gridEnumSanitizer(UserLifecycleStatus::class),
],
'trigger_types' => [
'type' => 'csv_strings',
'max' => 200,
'sanitizer' => gridEnumSanitizer(UserLifecycleTriggerType::class),
],
'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200],
'created_from' => ['type' => 'date'],
'created_to' => ['type' => 'date'],
'order' => ['type' => 'order', 'allowed' => ['created_at', 'status', 'action', 'trigger_type', 'restored_at'], 'default' => 'created_at'],
'dir' => ['type' => 'dir', 'default' => 'desc'],
],
'toolbar' => [
[
'key' => 'search',
'type' => 'text',
'label' => 'Search',
'placeholder' => 'Search...',
'input_id' => 'user-lifecycle-audit-search',
'search' => true,
'query' => ['type' => 'string'],
],
[
'key' => 'actions',
'type' => 'multi_csv',
'label' => 'Action',
'placeholder' => 'Select actions',
'input_id' => 'user-lifecycle-audit-actions-filter',
'options_key' => 'action_items',
'default' => [],
'query' => ['type' => 'csv_strings', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'statuses',
'type' => 'multi_csv',
'label' => 'Status',
'placeholder' => 'Select statuses',
'input_id' => 'user-lifecycle-audit-statuses-filter',
'options_key' => 'status_items',
'default' => [],
'query' => ['type' => 'csv_strings', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'trigger_types',
'type' => 'multi_csv',
'label' => 'Trigger',
'placeholder' => 'Select triggers',
'input_id' => 'user-lifecycle-audit-trigger-types-filter',
'options_key' => 'trigger_items',
'default' => [],
'query' => ['type' => 'csv_strings', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'actor_user_ids',
'type' => 'multi_csv',
'label' => 'Actor',
'placeholder' => 'Select actor users',
'input_id' => 'user-lifecycle-audit-actor-user-ids-filter',
'options_key' => 'actor_items',
'default' => [],
'query' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
],
[
'key' => 'created_from',
'type' => 'date',
'label' => 'Created from',
'input_id' => 'user-lifecycle-audit-created-from',
],
[
'key' => 'created_to',
'type' => 'date',
'label' => 'Created to',
'input_id' => 'user-lifecycle-audit-created-to',
],
],
]);

View File

@@ -1,218 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\UserLifecycleAuditService;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_AUDIT_PURGE
);
Buffer::set('title', t('User lifecycle logs'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
...gridSchemaQuery($filterSchema),
'actions' => [
'type' => 'csv_strings',
'max' => 200,
'return' => 'array',
'sanitizer' => gridEnumSanitizer(UserLifecycleAction::class),
],
'statuses' => [
'type' => 'csv_strings',
'max' => 200,
'return' => 'array',
'sanitizer' => gridEnumSanitizer(UserLifecycleStatus::class),
],
'trigger_types' => [
'type' => 'csv_strings',
'max' => 200,
'return' => 'array',
'sanitizer' => gridEnumSanitizer(UserLifecycleTriggerType::class),
],
'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(UserLifecycleAuditService::class)->filterOptions(200);
$activeActions = is_array($filterState['actions'] ?? null) ? $filterState['actions'] : [];
$activeStatuses = is_array($filterState['statuses'] ?? null) ? $filterState['statuses'] : [];
$activeTriggerTypes = is_array($filterState['trigger_types'] ?? null) ? $filterState['trigger_types'] : [];
$activeActorUserIds = array_map('strval', is_array($filterState['actor_user_ids'] ?? null) ? $filterState['actor_user_ids'] : []);
$actionLabelMap = [];
foreach (UserLifecycleAction::cases() as $actionCase) {
$actionLabelMap[$actionCase->value] = t($actionCase->labelToken());
}
$statusLabelMap = [];
foreach (UserLifecycleStatus::cases() as $statusCase) {
$statusLabelMap[$statusCase->value] = t($statusCase->labelToken());
}
$triggerLabelMap = [];
foreach (UserLifecycleTriggerType::cases() as $triggerCase) {
$triggerLabelMap[$triggerCase->value] = t($triggerCase->labelToken());
}
$lifecycleActionItems = [];
foreach (UserLifecycleAction::values() as $action) {
$lifecycleActionItems[$action] = [
'id' => $action,
'description' => $actionLabelMap[$action] ?? $action,
];
}
foreach ((array) ($filterOptions['actions'] ?? []) as $action) {
$action = strtolower(trim((string) $action));
if ($action === '') {
continue;
}
$lifecycleActionItems[$action] = [
'id' => $action,
'description' => $actionLabelMap[$action] ?? $action,
];
}
$lifecycleActionItems = array_values($lifecycleActionItems);
$lifecycleStatusItems = [];
foreach (UserLifecycleStatus::values() as $status) {
$lifecycleStatusItems[$status] = [
'id' => $status,
'description' => $statusLabelMap[$status] ?? $status,
];
}
foreach ((array) ($filterOptions['statuses'] ?? []) as $status) {
$status = strtolower(trim((string) $status));
if ($status === '') {
continue;
}
$lifecycleStatusItems[$status] = [
'id' => $status,
'description' => $statusLabelMap[$status] ?? $status,
];
}
$lifecycleStatusItems = array_values($lifecycleStatusItems);
$lifecycleTriggerItems = [];
foreach (UserLifecycleTriggerType::values() as $triggerType) {
$lifecycleTriggerItems[$triggerType] = [
'id' => $triggerType,
'description' => $triggerLabelMap[$triggerType] ?? $triggerType,
];
}
foreach ((array) ($filterOptions['trigger_types'] ?? []) as $triggerType) {
$triggerType = strtolower(trim((string) $triggerType));
if ($triggerType === '') {
continue;
}
$lifecycleTriggerItems[$triggerType] = [
'id' => $triggerType,
'description' => $triggerLabelMap[$triggerType] ?? $triggerType,
];
}
$lifecycleTriggerItems = array_values($lifecycleTriggerItems);
$lifecycleActorItems = [];
foreach ((array) ($filterOptions['actors'] ?? []) as $actorOption) {
if (!is_array($actorOption)) {
continue;
}
$actorId = (int) ($actorOption['id'] ?? 0);
if ($actorId <= 0) {
continue;
}
$actorDisplayName = trim((string) ($actorOption['display_name'] ?? ''));
$actorEmail = trim((string) ($actorOption['email'] ?? ''));
$actorExists = (bool) ($actorOption['exists'] ?? false);
$label = $actorDisplayName !== '' ? $actorDisplayName : $actorEmail;
if ($label === '') {
$label = $actorExists
? sprintf(t('User #%d'), $actorId)
: sprintf(t('User #%d (deleted)'), $actorId);
}
$id = (string) $actorId;
$lifecycleActorItems[$id] = [
'id' => $id,
'description' => $label,
];
}
foreach ($activeActorUserIds as $actorId) {
if (!isset($lifecycleActorItems[$actorId])) {
$lifecycleActorItems[$actorId] = [
'id' => $actorId,
'description' => sprintf(t('User #%d (deleted)'), (int) $actorId),
];
}
}
$lifecycleActorItems = array_values($lifecycleActorItems);
$toolbarFilterState = [
'search' => (string) ($filterState['search'] ?? ''),
'actions' => $activeActions,
'statuses' => $activeStatuses,
'trigger_types' => $activeTriggerTypes,
'actor_user_ids' => $activeActorUserIds,
'created_from' => (string) ($filterState['created_from'] ?? ''),
'created_to' => (string) ($filterState['created_to'] ?? ''),
];
$toolbarOptionSets = [
'action_items' => $lifecycleActionItems,
'status_items' => $lifecycleStatusItems,
'trigger_items' => $lifecycleTriggerItems,
'actor_items' => $lifecycleActorItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
'filter_state' => $filterState,
'search_keys' => ['search'],
'toolbar_state_overrides' => $toolbarFilterState,
'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
'search' => [
'label' => t('Search'),
'type' => 'text',
],
'actions' => [
'label' => t('Action'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($lifecycleActionItems),
],
'statuses' => [
'label' => t('Status'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($lifecycleStatusItems),
],
'trigger_types' => [
'label' => t('Trigger'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($lifecycleTriggerItems),
],
'actor_user_ids' => [
'label' => t('Actor'),
'type' => 'multi_csv',
'options' => gridOptionMapFromItems($lifecycleActorItems),
],
'created_range' => [
'label' => t('Created'),
'type' => 'date_range',
'from_param' => 'created_from',
'to_param' => 'created_to',
],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];

View File

@@ -1,73 +0,0 @@
<?php
$pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canPurge = (bool) ($pageAuth['can_purge'] ?? false);
$toolbarFilterSchema = is_array($toolbarFilterSchema ?? null) ? $toolbarFilterSchema : [];
$searchToolbarFilterSchema = is_array($searchToolbarFilterSchema ?? null) ? $searchToolbarFilterSchema : [];
$drawerToolbarFilterSchema = is_array($drawerToolbarFilterSchema ?? null) ? $drawerToolbarFilterSchema : [];
$toolbarFilterState = is_array($toolbarFilterState ?? null) ? $toolbarFilterState : [];
$toolbarOptionSets = is_array($toolbarOptionSets ?? null) ? $toolbarOptionSets : [];
$filterChipMeta = is_array($filterChipMeta ?? null) ? $filterChipMeta : [];
$clientFilterSchema = is_array($clientFilterSchema ?? null) ? $clientFilterSchema : [];
$searchConfig = is_array($searchConfig ?? null) ? $searchConfig : null;
?>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('User lifecycle logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<?php
$listTitle = t('User lifecycle logs');
ob_start();
?>
<?php
$listPurgeEnabled = $canPurge;
$listPurgeFormId = 'user-lifecycle-audit-purge-form';
$listPurgeAction = 'admin/user-lifecycle-audit/purge';
$listPurgeConfirmMessage = t('Purge entries older than 365 days?');
$listPurgeButtonLabel = t('Purge user lifecycle logs');
require templatePath('partials/app-list-purge-action.phtml');
?>
<?php
$listTitleActionsHtml = ob_get_clean();
require templatePath('partials/app-list-titlebar.phtml');
?>
<?php
$filterUiNamespace = 'user-lifecycle';
$filterToolbarId = 'user-lifecycle-audit-toolbar';
$filterDrawerToolbarId = 'user-lifecycle-drawer-toolbar';
$filterDrawerTitleId = 'user-lifecycle-filter-drawer-title';
require templatePath('partials/app-list-filters.phtml');
?>
<div class="app-list-table">
<div id="user-lifecycle-audit-grid"></div>
</div>
<?php
$gridLang = json_decode(appBufferValue('grid_lang'), true);
if (!is_array($gridLang)) {
$gridLang = [];
}
$pageConfig = [
'gridSearch' => $searchConfig,
'filterSchema' => $clientFilterSchema,
'filterChipMeta' => $filterChipMeta,
'gridLang' => $gridLang,
'labels' => [
'created' => t('Created'),
'status' => t('Status'),
'action' => t('Action'),
'trigger' => t('Trigger'),
'targetEmail' => t('Target email'),
'targetUuid' => t('Target UUID'),
'reasonCode' => t('Reason code'),
'restoredAt' => t('Restored at'),
],
];
?>
<script src="<?php e(assetVersion('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="application/json" id="page-config-admin-user-lifecycle-audit-index"><?php gridJsonForJs($pageConfig); ?></script>
<script type="module" src="<?php e(assetVersion('js/pages/admin-user-lifecycle-audit-index.js')); ?>"></script>

View File

@@ -1,27 +0,0 @@
<?php
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE);
if (strtoupper((string) (requestInput()->method())) !== 'POST') {
Router::redirect('admin/user-lifecycle-audit');
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, 'admin/user-lifecycle-audit', 'user_lifecycle_audit');
Router::redirect('admin/user-lifecycle-audit');
}
$deleted = app(\MintyPHP\Service\Audit\UserLifecycleAuditService::class)->purgeExpired();
Flash::success(
sprintf(t('%d user lifecycle audit entries purged'), $deleted),
'admin/user-lifecycle-audit',
'user_lifecycle_audit_purged'
);
Router::redirect('admin/user-lifecycle-audit');

View File

@@ -1,48 +0,0 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_USERS_LIFECYCLE_RESTORE);
$auditId = (int) ($id ?? 0);
$errorBag = formErrors();
if (strtoupper((string) (requestInput()->method())) !== 'POST') {
Router::redirect('admin/user-lifecycle-audit');
}
if (!Session::checkCsrfToken()) {
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, 'admin/user-lifecycle-audit', 'user_lifecycle_restore');
Router::redirect('admin/user-lifecycle-audit');
}
$result = app(\MintyPHP\Service\User\UserLifecycleRestoreService::class)->restoreFromLifecycleAudit(
$auditId,
(int) ($session['user']['id'] ?? 0)
);
if (!($result['ok'] ?? false)) {
$error = (string) ($result['error'] ?? 'restore_unexpected_error');
if ($error === 'restore_email_exists') {
$errorBag->addGlobal(t('Restore not possible: email already exists'));
} elseif ($error === 'restore_uuid_exists') {
$errorBag->addGlobal(t('Restore not possible: uuid already exists'));
} elseif ($error === 'snapshot_unavailable') {
$errorBag->addGlobal(t('Lifecycle snapshot unavailable'));
} elseif ($error === 'audit_event_already_restored') {
$errorBag->addGlobal(t('Lifecycle event was already restored'));
} else {
$errorBag->addGlobal(t('User restore failed'));
}
flashFormErrors($errorBag, "admin/user-lifecycle-audit/view/$auditId", 'user_lifecycle_restore');
Router::redirect("admin/user-lifecycle-audit/view/$auditId");
}
Flash::success(t('User restored'), "admin/user-lifecycle-audit/view/$auditId", 'user_restored');
Router::redirect("admin/user-lifecycle-audit/view/$auditId");

View File

@@ -1,33 +0,0 @@
<?php
use MintyPHP\Buffer;
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW);
$auditId = (int) ($id ?? 0);
$auditService = app(\MintyPHP\Service\Audit\UserLifecycleAuditService::class);
$auditLog = $auditId > 0 ? $auditService->find($auditId) : null;
if (!$auditLog) {
Flash::error(t('Lifecycle audit entry not found'), 'admin/user-lifecycle-audit', 'user_lifecycle_audit_not_found');
Router::redirect('admin/user-lifecycle-audit');
}
$snapshot = null;
if ((string) ($auditLog['action'] ?? '') === UserLifecycleAction::Delete->value) {
$snapshot = $auditService->decryptSnapshot($auditLog);
}
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
(int) ($session['user']['id'] ?? 0),
UiCapabilityMap::PAGE_USER_LIFECYCLE_VIEW
);
Buffer::set('title', t('View user lifecycle audit entry'));

View File

@@ -1,213 +0,0 @@
<?php
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
/**
* @var array $auditLog
* @var ?array $snapshot
*/
use MintyPHP\Session;
$auditLog = $auditLog ?? [];
$snapshot = is_array($snapshot ?? null) ? $snapshot : null;
$status = UserLifecycleStatus::normalizeOr((string) ($auditLog['status'] ?? ''), UserLifecycleStatus::Failed);
$statusVariant = $status->badgeVariant();
$action = UserLifecycleAction::normalizeOr((string) ($auditLog['action'] ?? ''), UserLifecycleAction::Deactivate);
$triggerType = UserLifecycleTriggerType::normalizeOr((string) ($auditLog['trigger_type'] ?? ''), UserLifecycleTriggerType::System);
$pageAuth = is_array($viewAuth['page'] ?? null) ? $viewAuth['page'] : [];
$canRestore = (bool) ($pageAuth['can_restore'] ?? false);
$isRestorable = $canRestore
&& $action === UserLifecycleAction::Delete
&& $status === UserLifecycleStatus::Success
&& empty($auditLog['restored_at'])
&& !empty($auditLog['snapshot_enc']);
?>
<div class="app-details-container">
<section>
<?php
$breadcrumbs = [
['label' => t('Home'), 'path' => 'admin'],
['label' => t('User lifecycle logs'), 'path' => 'admin/user-lifecycle-audit'],
['label' => t('View')],
];
require templatePath('partials/app-breadcrumb.phtml');
$titlebar = [
'title' => t('View user lifecycle audit entry'),
'backHref' => 'admin/user-lifecycle-audit',
'backTitle' => t('Back'),
];
require templatePath('partials/app-details-titlebar.phtml');
?>
<div class="app-details-content">
<details open>
<summary><?php e(t('Lifecycle event')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Created')); ?></small>
<p><?php e(dt((string) ($auditLog['created_at'] ?? '')) ?: '-'); ?></p>
</div>
<div>
<small><?php e(t('Status')); ?></small>
<p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Action')); ?></small>
<p><?php e(t($action->labelToken())); ?></p>
</div>
<div>
<small><?php e(t('Trigger')); ?></small>
<p><?php e(t($triggerType->labelToken())); ?></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Reason code')); ?></small>
<p><?php e((string) ($auditLog['reason_code'] ?? '') !== '' ? (string) $auditLog['reason_code'] : '-'); ?></p>
</div>
<div>
<small><?php e(t('Run UUID')); ?></small>
<p><?php e((string) ($auditLog['run_uuid'] ?? '') !== '' ? (string) $auditLog['run_uuid'] : '-'); ?></p>
</div>
</div>
</details>
<hr>
<details open>
<summary><?php e(t('Target')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Target UUID')); ?></small>
<p><?php e((string) ($auditLog['target_user_uuid'] ?? '') !== '' ? (string) $auditLog['target_user_uuid'] : '-'); ?></p>
</div>
<div>
<small><?php e(t('Target email')); ?></small>
<p><?php e((string) ($auditLog['target_user_email'] ?? '') !== '' ? (string) $auditLog['target_user_email'] : '-'); ?></p>
</div>
</div>
</details>
<hr>
<details>
<summary><?php e(t('Policy')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Deactivate users after inactivity (days)')); ?></small>
<p><?php e((string) ((int) ($auditLog['policy_deactivate_days'] ?? 0))); ?></p>
</div>
<div>
<small><?php e(t('Delete inactive users after (days)')); ?></small>
<p><?php e((string) ((int) ($auditLog['policy_delete_days'] ?? 0))); ?></p>
</div>
</div>
</details>
<?php if ($snapshot !== null): ?>
<hr>
<details>
<summary><?php e(t('Snapshot summary')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('First name')); ?></small>
<p><?php e((string) ($snapshot['first_name'] ?? '') !== '' ? (string) $snapshot['first_name'] : '-'); ?></p>
</div>
<div>
<small><?php e(t('Last name')); ?></small>
<p><?php e((string) ($snapshot['last_name'] ?? '') !== '' ? (string) $snapshot['last_name'] : '-'); ?></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Email')); ?></small>
<p><?php e((string) ($snapshot['email'] ?? '') !== '' ? (string) $snapshot['email'] : '-'); ?></p>
</div>
<div>
<small><?php e(t('Locale')); ?></small>
<p><?php e((string) ($snapshot['locale'] ?? '') !== '' ? (string) $snapshot['locale'] : '-'); ?></p>
</div>
</div>
<div class="grid">
<div>
<small><?php e(t('Theme')); ?></small>
<p><?php e((string) ($snapshot['theme'] ?? '') !== '' ? (string) $snapshot['theme'] : '-'); ?></p>
</div>
<div>
<small><?php e(t('Snapshot version')); ?></small>
<p><?php e((string) ((int) ($auditLog['snapshot_version'] ?? 1))); ?></p>
</div>
</div>
</details>
<?php endif; ?>
<hr>
<details open>
<summary><?php e(t('Restore status')); ?></summary>
<hr>
<div class="grid">
<div>
<small><?php e(t('Restored at')); ?></small>
<p><?php e(dt((string) ($auditLog['restored_at'] ?? '')) ?: '-'); ?></p>
</div>
<div>
<small><?php e(t('Restored by')); ?></small>
<p><?php e((string) ($auditLog['restored_by_user_display_name'] ?? '') !== '' ? (string) $auditLog['restored_by_user_display_name'] : '-'); ?></p>
</div>
</div>
<div>
<small><?php e(t('Restored user')); ?></small>
<p>
<?php if (!empty($auditLog['restored_user_uuid'])): ?>
<a href="admin/users/edit/<?php e((string) $auditLog['restored_user_uuid']); ?>">
<?php e((string) ($auditLog['restored_user_display_name'] ?? $auditLog['restored_user_uuid'])); ?>
</a>
<?php else: ?>
-
<?php endif; ?>
</p>
</div>
<?php if ($isRestorable): ?>
<hr>
<form method="post" action="admin/user-lifecycle-audit/restore/<?php e((string) ($auditLog['id'] ?? 0)); ?>">
<?php Session::getCsrfInput(); ?>
<button type="submit" class="warning" data-confirm-message="<?php e(t('Restore this user from lifecycle snapshot?')); ?>">
<?php e(t('Restore user')); ?>
</button>
</form>
<?php endif; ?>
</details>
</div>
</section>
<aside id="app-details-aside-section">
<div class="app-details-aside-section">
<hgroup>
<strong><?php e(t('User lifecycle logs')); ?></strong>
<p><small><?php e((string) ($auditLog['run_uuid'] ?? '') !== '' ? (string) $auditLog['run_uuid'] : '-'); ?></small></p>
</hgroup>
<hr>
<div>
<small><?php e(t('ID')); ?></small>
<p><span class="badge" data-variant="neutral"><?php e((string) ($auditLog['id'] ?? '-')); ?></span></p>
</div>
<div>
<small><?php e(t('Status')); ?></small>
<p><span class="badge" data-variant="<?php e($statusVariant); ?>"><?php e(t($status->labelToken())); ?></span></p>
</div>
<div>
<small><?php e(t('Action')); ?></small>
<p><?php e(t($action->labelToken())); ?></p>
</div>
</div>
</aside>
</div>