Files
breadcrumb-the-shire/pages/admin/departments/data().php

67 lines
2.7 KiB
PHP

<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Support\Guard;
$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
gridRequireGetRequest();
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = Guard::requireAbilityDecisionOrForbidden(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW);
$capabilities = $decision->attribute('capabilities', []);
$tenantIds = is_array($capabilities) ? array_values(array_unique(array_map('intval', (array) ($capabilities['allowed_tenant_ids'] ?? [])))) : [];
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$result = app(\MintyPHP\Service\Org\DepartmentService::class)->listPaged([
'limit' => $filters['limit'],
'offset' => $filters['offset'],
'search' => $filters['search'],
'order' => $filters['order'],
'dir' => $filters['dir'],
'tenant' => $filters['tenant'],
'active' => $filters['active'],
'tenantIds' => $tenantIds,
'tenantUserId' => $currentUserId,
]);
$settingsDefaultsGateway = app(\MintyPHP\Service\Settings\SettingsDefaultsGateway::class);
$defaultDepartmentId = $settingsDefaultsGateway->getDefaultDepartmentId();
$departmentIds = [];
foreach ($result['rows'] as $departmentRow) {
$departmentId = (int) ($departmentRow['id'] ?? 0);
if ($departmentId > 0) {
$departmentIds[] = $departmentId;
}
}
$departmentIds = array_values(array_unique($departmentIds));
$userDepartmentRepository = app(\MintyPHP\Repository\Org\UserDepartmentRepository::class);
$departmentUserCounts = $userDepartmentRepository->countUsersByDepartmentIds($departmentIds);
$departmentActiveUserCounts = $userDepartmentRepository->countActiveUsersByDepartmentIds($departmentIds);
$rows = [];
foreach ($result['rows'] as $row) {
$departmentId = (int) ($row['id'] ?? 0);
$usersTotal = (int) ($departmentUserCounts[$departmentId] ?? 0);
$usersActive = (int) ($departmentActiveUserCounts[$departmentId] ?? 0);
$usersInactive = max(0, $usersTotal - $usersActive);
$rows[] = [
'id' => $row['id'] ?? null,
'uuid' => $row['uuid'] ?? '',
'is_default' => $departmentId > 0 && $defaultDepartmentId === $departmentId,
'description' => $row['description'] ?? '',
'code' => $row['code'] ?? '',
'cost_center' => $row['cost_center'] ?? '',
'active' => $row['active'] ?? 1,
'active_users' => $usersActive,
'inactive_users' => $usersInactive,
'tenants' => $row['tenant_labels'] ?? [],
'created' => dt($row['created'] ?? ''),
'modified' => dt($row['modified'] ?? ''),
];
}
gridJsonDataResult($rows, (int) ($result['total'] ?? 0));