Files
breadcrumb-the-shire/lib/Service/Org/DepartmentService.php
fs 25370a1a55 add composer-unused, comprehensive docs, and project restructure
- Add icanhazstring/composer-unused as dev dependency for dependency hygiene checks
- Add German documentation (docs/) covering architecture, conventions, workflows, and developer checklists
- Add API layer (ApiAuth, ApiBootstrap, ApiResponse), audit, scheduler, custom fields, and SSO services
- Add Microsoft OIDC SSO, API token management, and user lifecycle features
- Add swagger-ui vendor integration and OpenAPI spec
- Add production Docker setup and bin/ scripts
- Update composer dependencies, config, templates, and frontend assets throughout

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-22 15:27:35 +01:00

244 lines
8.1 KiB
PHP

<?php
namespace MintyPHP\Service\Org;
use MintyPHP\Repository\Org\DepartmentRepository;
use MintyPHP\Repository\Org\UserDepartmentRepository;
use MintyPHP\Service\Settings\SettingService;
use MintyPHP\Service\Tenant\TenantScopeService;
class DepartmentService
{
public static function list(): array
{
return DepartmentRepository::list();
}
public static function listPaged(array $options): array
{
if (!empty($options['tenantUserId'])) {
$tenantUserId = (int) $options['tenantUserId'];
if ($tenantUserId > 0 && TenantScopeService::hasGlobalAccess($tenantUserId)) {
unset($options['tenantUserId'], $options['tenantIds']);
}
}
return DepartmentRepository::listPaged($options);
}
public static function listByTenantIds(array $tenantIds): array
{
return DepartmentRepository::listByTenantIds($tenantIds);
}
public static function groupActiveByTenantIds(array $tenantIds): array
{
$tenantIds = array_values(array_unique(array_map('intval', $tenantIds)));
$tenantIds = array_values(array_filter($tenantIds, static fn ($id) => $id > 0));
if (!$tenantIds) {
return [];
}
$departments = self::listByTenantIds($tenantIds);
if (!$departments) {
return [];
}
$grouped = [];
foreach ($departments as $department) {
$tenantId = (int) ($department['tenant_id'] ?? 0);
if ($tenantId <= 0) {
continue;
}
$grouped[$tenantId] ??= [];
$grouped[$tenantId][] = $department;
}
foreach ($grouped as &$items) {
usort($items, static function (array $a, array $b): int {
return strcmp((string) ($a['description'] ?? ''), (string) ($b['description'] ?? ''));
});
}
unset($items);
return $grouped;
}
public static function listByIds(array $departmentIds): array
{
return DepartmentRepository::listByIds($departmentIds);
}
public static function listForUserAssignments(array $tenantIds, array $selectedDepartmentIds): array
{
$departments = $tenantIds ? self::listByTenantIds($tenantIds) : self::list();
$extraDepartments = $selectedDepartmentIds ? self::listByIds($selectedDepartmentIds) : [];
if (!$extraDepartments) {
return $departments;
}
$departmentMap = [];
foreach ($departments as $department) {
if (isset($department['id'])) {
$departmentMap[(int) $department['id']] = $department;
}
}
foreach ($extraDepartments as $department) {
if (isset($department['id'])) {
$departmentMap[(int) $department['id']] = $department;
}
}
return array_values($departmentMap);
}
public static function findByUuid(string $uuid): ?array
{
return DepartmentRepository::findByUuid($uuid);
}
public static function findById(int $id): ?array
{
return DepartmentRepository::find($id);
}
public static function createFromAdmin(array $input, int $currentUserId = 0): array
{
$form = self::sanitizeBase($input);
$errors = self::validateBase($form);
$warnings = self::warningsForCode($form, 0);
if ($errors) {
return ['ok' => false, 'errors' => $errors, 'warnings' => $warnings, 'form' => $form];
}
$createdId = DepartmentRepository::create([
'description' => $form['description'],
'tenant_id' => $form['tenant_id'],
'code' => $form['code'] ?: null,
'cost_center' => $form['cost_center'] ?: null,
'active' => $form['active'],
'created_by' => $currentUserId > 0 ? $currentUserId : null,
]);
if (!$createdId) {
return ['ok' => false, 'errors' => [t('Department can not be created')], 'form' => $form];
}
$createdDepartment = DepartmentRepository::find((int) $createdId);
$uuid = $createdDepartment['uuid'] ?? null;
if (!empty($input['is_default'])) {
SettingService::setDefaultDepartmentId((int) $createdId);
}
return ['ok' => true, 'form' => $form, 'warnings' => $warnings, 'uuid' => $uuid, 'id' => (int) $createdId];
}
public static function updateFromAdmin(int $departmentId, array $input, int $currentUserId = 0): array
{
$form = self::sanitizeBase($input);
$errors = self::validateBase($form);
$warnings = self::warningsForCode($form, $departmentId);
if ($errors) {
return ['ok' => false, 'errors' => $errors, 'warnings' => $warnings, 'form' => $form];
}
$updated = DepartmentRepository::update($departmentId, [
'description' => $form['description'],
'tenant_id' => $form['tenant_id'],
'code' => $form['code'] ?: null,
'cost_center' => $form['cost_center'] ?: null,
'active' => $form['active'],
'modified_by' => $currentUserId > 0 ? $currentUserId : null,
]);
if (!$updated) {
return ['ok' => false, 'errors' => [t('Department can not be updated')], 'form' => $form];
}
return ['ok' => true, 'form' => $form, 'warnings' => $warnings];
}
public static function syncTenant(int $departmentId, int $tenantId): int
{
$updated = DepartmentRepository::setTenant($departmentId, $tenantId);
if (!$updated) {
return -1;
}
return self::cleanupUserAssignments($departmentId);
}
public static function syncTenants(int $departmentId, array $tenantIds): int
{
$tenantId = (int) ($tenantIds[0] ?? 0);
if ($tenantId <= 0) {
return -1;
}
return self::syncTenant($departmentId, $tenantId);
}
public static function cleanupUserAssignments(int $departmentId): int
{
return UserDepartmentRepository::removeInvalidForDepartment($departmentId);
}
public static function deleteByUuid(string $uuid): array
{
$uuid = trim($uuid);
if ($uuid === '') {
return ['ok' => false, 'status' => 404, 'error' => 'not_found'];
}
$department = DepartmentRepository::findByUuid($uuid);
if (!$department || !isset($department['id'])) {
return ['ok' => false, 'status' => 404, 'error' => 'not_found'];
}
$deleted = DepartmentRepository::delete((int) $department['id']);
if (!$deleted) {
return ['ok' => false, 'status' => 500, 'error' => 'delete_failed'];
}
return ['ok' => true, 'department' => $department];
}
private static function sanitizeBase(array $input): array
{
return [
'description' => trim((string) ($input['description'] ?? '')),
'tenant_id' => (int) ($input['tenant_id'] ?? 0),
'code' => trim((string) ($input['code'] ?? '')),
'cost_center' => trim((string) ($input['cost_center'] ?? '')),
'active' => self::normalizeActive($input['active'] ?? 1),
];
}
private static function validateBase(array $form): array
{
$errors = [];
if ($form['description'] === '') {
$errors[] = t('Description cannot be empty');
}
if ((int) ($form['tenant_id'] ?? 0) <= 0) {
$errors[] = t('Please select at least one tenant');
}
return $errors;
}
private static function warningsForCode(array $form, int $excludeId): array
{
$warnings = [];
$code = $form['code'] ?? '';
if ($code !== '' && DepartmentRepository::existsByCode($code, $excludeId)) {
$warnings[] = t('Department code already exists');
}
return $warnings;
}
private static function normalizeActive($value): int
{
$value = strtolower(trim((string) $value));
if (in_array($value, ['0', 'false', 'inactive'], true)) {
return 0;
}
return 1;
}
}