refactor(admin/users): migrate CSV export to core primitive

Replace the inline export implementation with the new generic primitive
(core/Service/Export + helpers/export + app-list-export.js). No more
hand-rolled fputcsv loop, header setup, or escape closure duplicated
here — one implementation, tested once, reused everywhere.

- export().php: uses exportRequireGetRequest, exportCapLimit,
  exportResolveFlavor, ExportColumn[], exportSendCsv. Phone/mobile/
  short_dial keep allowSignedNumeric=true so +49 numbers render
  untouched.
- export(none).phtml: deleted — headers + fputcsv now live in the
  core helper.
- index(default).phtml: inline <details class="dropdown"> "Export CSV"
  replaced by the reusable app-list-export-dropdown partial, exposing
  CSV and Excel flavors. exportUrl added to pageConfig.
- app-users-list.js: hand-rolled export-button binding removed in
  favor of initListExport({ gridConfig, exportUrl }).
- admin-users-index.js: forwards config.exportUrl into
  initUsersListPage.

Net effect: ~100 lines of duplicated export plumbing removed from the
users page; users gain the Excel flavor for free.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-21 21:57:31 +02:00
parent 12356e2266
commit 5ba086adee
5 changed files with 68 additions and 121 deletions

View File

@@ -4,10 +4,13 @@ use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\Export\ExportColumn;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
exportRequireGetRequest();
$session = app(SessionStoreInterface::class)->all();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW, [
'actor_user_id' => (int) ($session['user']['id'] ?? 0),
@@ -21,34 +24,28 @@ if (!$decision->isAllowed()) {
Router::redirect('error/forbidden?url=' . urlencode(Request::pathWithQuery()));
return;
}
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$request = requestInput();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$search = trim((string) (requestInput()->queryAll()['search'] ?? ''));
$order = (string) (requestInput()->queryAll()['order'] ?? 'id');
$dir = strtolower((string) (requestInput()->queryAll()['dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
$active = requestInput()->queryAll()['active'] ?? 'all';
$createdFrom = trim((string) (requestInput()->queryAll()['created_from'] ?? ''));
$createdTo = trim((string) (requestInput()->queryAll()['created_to'] ?? ''));
$tenant = trim((string) (requestInput()->queryAll()['tenant'] ?? ''));
$roles = requestInput()->queryAll()['roles'] ?? '';
$departments = requestInput()->queryAll()['departments'] ?? '';
$search = $request->queryString('search');
$order = (string) $request->query('order', 'id');
$dir = strtolower((string) $request->query('dir', 'desc')) === 'asc' ? 'asc' : 'desc';
$active = (string) $request->query('active', 'all');
$createdFrom = $request->queryString('created_from');
$createdTo = $request->queryString('created_to');
$tenant = $request->queryString('tenant');
$roles = $request->query('roles', '');
$departments = $request->query('departments', '');
$allowedOrder = ['id', 'uuid', 'first_name', 'last_name', 'email', 'locale', 'theme', 'created', 'modified', 'active'];
if (!in_array($order, $allowedOrder, true)) {
$order = 'id';
}
$limit = (int) (requestInput()->queryAll()['limit'] ?? 5000);
if ($limit < 1) {
$limit = 5000;
}
if ($limit > 5000) {
$limit = 5000;
}
$limit = exportCapLimit($request->query('limit'), 5000);
$result = $userAccountService->listPaged([
$result = app(\MintyPHP\Service\User\UserAccountService::class)->listPaged([
'limit' => $limit,
'offset' => 0,
'search' => $search,
@@ -63,5 +60,48 @@ $result = $userAccountService->listPaged([
'tenantUserId' => $currentUserId,
]);
$exportRows = $result['rows'] ?? [];
$exportFilename = 'users-' . date('Ymd-His') . '.csv';
$joinLabels = static function (mixed $value): string {
if (is_array($value)) {
return implode(' | ', array_map('strval', $value));
}
if (is_string($value)) {
$trimmed = trim($value);
if ($trimmed === '') {
return '';
}
return str_replace('||', ' | ', $trimmed);
}
return '';
};
$formatTimestamp = static function (mixed $value): string {
if ($value === null || $value === '') {
return '';
}
return (string) dt($value, 'Y-m-d H:i:s');
};
$columns = [
new ExportColumn('id', static fn (array $r): string => (string) ($r['id'] ?? '')),
new ExportColumn('uuid', static fn (array $r): string => (string) ($r['uuid'] ?? '')),
new ExportColumn('first_name', static fn (array $r): string => (string) ($r['first_name'] ?? '')),
new ExportColumn('last_name', static fn (array $r): string => (string) ($r['last_name'] ?? '')),
new ExportColumn('email', static fn (array $r): string => (string) ($r['email'] ?? '')),
new ExportColumn('phone', static fn (array $r): string => (string) ($r['phone'] ?? ''), allowSignedNumeric: true),
new ExportColumn('mobile', static fn (array $r): string => (string) ($r['mobile'] ?? ''), allowSignedNumeric: true),
new ExportColumn('short_dial', static fn (array $r): string => (string) ($r['short_dial'] ?? ''), allowSignedNumeric: true),
new ExportColumn('locale', static fn (array $r): string => (string) ($r['locale'] ?? '')),
new ExportColumn('theme', static fn (array $r): string => (string) ($r['theme'] ?? '')),
new ExportColumn('active', static fn (array $r): int => (int) ($r['active'] ?? 0)),
new ExportColumn('tenants', static fn (array $r): string => $joinLabels($r['tenant_labels'] ?? [])),
new ExportColumn('departments', static fn (array $r): string => $joinLabels($r['department_labels'] ?? [])),
new ExportColumn('roles', static fn (array $r): string => $joinLabels($r['role_labels'] ?? [])),
new ExportColumn('created_by', static fn (array $r): string => (string) ($r['created_by'] ?? '')),
new ExportColumn('modified_by', static fn (array $r): string => (string) ($r['modified_by'] ?? '')),
new ExportColumn('created', static fn (array $r): string => $formatTimestamp($r['created'] ?? '')),
new ExportColumn('modified', static fn (array $r): string => $formatTimestamp($r['modified'] ?? '')),
];
$filename = 'users-' . date('Ymd-His') . '.csv';
exportSendCsv($filename, $result['rows'] ?? [], $columns, exportResolveFlavor($request));

View File

@@ -1,75 +0,0 @@
<?php
$filename = $exportFilename ?? ('users-' . date('Ymd-His') . '.csv');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
$escapeValue = static function ($value, bool $allowSignedNumeric = false) {
if ($value === null) {
return '';
}
$string = (string) $value;
if ($string !== '' && in_array($string[0], ['=', '@'], true)) {
return "'" . $string;
}
if ($string !== '' && in_array($string[0], ['+', '-'], true)) {
if ($allowSignedNumeric && preg_match('/^[+-]?[0-9\\s().-]+$/', $string)) {
return $string;
}
return "'" . $string;
}
return $string;
};
$formatTimestamp = static function ($value) {
if ($value === null || $value === '') {
return '';
}
return dt($value, 'Y-m-d H:i:s');
};
$joinLabels = static function ($value) {
if (is_array($value)) {
return implode(' | ', array_map('strval', $value));
}
if (is_string($value)) {
$value = trim($value);
if ($value === '') {
return '';
}
return str_replace('||', ' | ', $value);
}
return '';
};
$handle = fopen('php://output', 'w');
if ($handle === false) {
return;
}
fputcsv($handle, ['id', 'uuid', 'first_name', 'last_name', 'email', 'phone', 'mobile', 'short_dial', 'locale', 'theme', 'active', 'tenants', 'departments', 'roles', 'created_by', 'modified_by', 'created', 'modified'], ',', '"', '\\');
foreach (($exportRows ?? []) as $row) {
fputcsv($handle, [
$escapeValue($row['id'] ?? ''),
$escapeValue($row['uuid'] ?? ''),
$escapeValue($row['first_name'] ?? ''),
$escapeValue($row['last_name'] ?? ''),
$escapeValue($row['email'] ?? ''),
$escapeValue($row['phone'] ?? '', true),
$escapeValue($row['mobile'] ?? '', true),
$escapeValue($row['short_dial'] ?? '', true),
$escapeValue($row['locale'] ?? ''),
$escapeValue($row['theme'] ?? ''),
(int) ($row['active'] ?? 0),
$escapeValue($joinLabels($row['tenant_labels'] ?? [])),
$escapeValue($joinLabels($row['department_labels'] ?? [])),
$escapeValue($joinLabels($row['role_labels'] ?? [])),
$escapeValue($row['created_by'] ?? ''),
$escapeValue($row['modified_by'] ?? ''),
$formatTimestamp($row['created'] ?? ''),
$formatTimestamp($row['modified'] ?? ''),
], ',', '"', '\\');
}
fclose($handle);

View File

@@ -46,16 +46,7 @@ ob_start();
<i class="bi bi-trash3-fill"></i> <?php e(t('Delete')); ?>
</button>
<?php endif; ?>
<details class="dropdown" data-tooltip="<?php e(t("Actions")); ?>" data-tooltip-pos="top">
<summary role="button" class="outline secondary"><i class="bi bi-three-dots"></i></summary>
<ul dir="rtl">
<li dir="ltr">
<button class="transparent" type="button" data-users-export>
<?php e(t('Export CSV')); ?>
</button>
</li>
</ul>
</details>
<?php require templatePath('partials/app-list-export-dropdown.phtml'); ?>
<?php if ($canCreateUser): ?>
<a role="button" class="app-action-success" href="<?php e(requestPathWithReturnTarget('admin/users/create', Request::pathWithQuery())); ?>">
@@ -119,6 +110,7 @@ $pageConfig = [
'gridSearch' => $searchConfig,
'filterSchema' => $clientFilterSchema,
'filterChipMeta' => $filterChipMeta,
'exportUrl' => lurl('admin/users/export'),
'currentUserUuid' => (string) $currentUserUuid,
'canUpdateUsers' => (bool) $canUpdateUsers,
'canUpdateSelf' => (bool) $canUpdateSelf,