Files
breadcrumb-the-shire/pages/admin/users/create().php
2026-02-04 23:31:53 +01:00

94 lines
3.1 KiB
PHP

<?php
use MintyPHP\Buffer;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;
use MintyPHP\I18n;
use MintyPHP\Router;
use MintyPHP\Service\PermissionService;
use MintyPHP\Service\UserService;
use MintyPHP\Service\TenantScopeService;
use MintyPHP\Service\TenantService;
use MintyPHP\Service\RoleService;
use MintyPHP\Service\DepartmentService;
use MintyPHP\Service\SettingService;
Guard::requirePermissionOrForbidden(PermissionService::USERS_CREATE);
$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$allowedTenantIds = TenantScopeService::getUserTenantIds($currentUserId);
$tenants = TenantService::list();
if ($allowedTenantIds) {
$tenants = array_values(array_filter($tenants, static function (array $tenant) use ($allowedTenantIds): bool {
$tenantId = (int) ($tenant['id'] ?? 0);
return $tenantId > 0 && in_array($tenantId, $allowedTenantIds, true);
}));
} elseif (TenantScopeService::isStrict()) {
$tenants = [];
}
$roles = RoleService::list();
$departments = $allowedTenantIds ? DepartmentService::listByTenantIds($allowedTenantIds) : [];
if (!$allowedTenantIds && !TenantScopeService::isStrict()) {
$departments = DepartmentService::list();
}
$errors = [];
$form = [
'first_name' => '',
'last_name' => '',
'email' => '',
'profile_description' => '',
'job_title' => '',
'phone' => '',
'mobile' => '',
'short_dial' => '',
'address' => '',
'postal_code' => '',
'city' => '',
'country' => '',
'region' => '',
'hire_date' => '',
'totp_secret' => '',
'locale' => I18n::$locale ?? I18n::$defaultLocale,
'active' => 1,
];
if (isset($_POST['email'])) {
$input = $_POST;
$tenantIds = UserService::normalizeIdInput($input['tenant_ids'] ?? []);
if ($allowedTenantIds) {
$tenantIds = array_values(array_intersect($tenantIds, $allowedTenantIds));
} elseif (TenantScopeService::isStrict()) {
$tenantIds = [];
}
$defaultTenantId = SettingService::getDefaultTenantId();
if (TenantScopeService::isStrict() && !$tenantIds && !$defaultTenantId) {
$errors[] = t('Please select at least one tenant');
}
$input['tenant_ids'] = $tenantIds;
$result = UserService::createFromAdmin($input, $currentUserId);
$form = $result['form'] ?? $form;
$errors = array_merge($errors, $result['errors'] ?? []);
if (($result['ok'] ?? false) && !$errors) {
$action = (string) ($_POST['action'] ?? 'create');
if ($action === 'create_close') {
Flash::success('User created', 'admin/users', 'user_created');
Router::redirect('admin/users');
} else {
$uuid = (string) ($result['uuid'] ?? '');
if ($uuid !== '') {
$target = "admin/users/edit/{$uuid}";
Flash::success('User created', $target, 'user_created');
Router::redirect($target);
} else {
Flash::success('User created', 'admin/users', 'user_created');
Router::redirect('admin/users');
}
}
}
}
Buffer::set('title', t('Create user'));