Files
deskhub/DeskHub-Webseite/api/staff/v1/organizations.php
T
2026-10-16 19:12:13 +00:00

55 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/common.php';
api_require_method('GET', 'POST');
$staff = api_require_staff();
api_require_admin_or_permission($staff, 'manage_organizations');
$pdo = get_db();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$organizations = $pdo->query(
'SELECT o.*, (SELECT COUNT(*) FROM users u WHERE u.organization_id = o.id) AS member_count
FROM organizations o ORDER BY o.name'
)->fetchAll();
api_json(['items' => array_map(fn(array $o) => [
'id' => (int) $o['id'],
'name' => $o['name'],
'notes' => $o['notes'],
'memberCount' => (int) $o['member_count'],
], $organizations)]);
}
$body = api_request_body();
$action = $body['action'] ?? '';
if ($action === 'save') {
$id = (int) ($body['id'] ?? 0);
$name = trim((string) ($body['name'] ?? ''));
$notes = trim((string) ($body['notes'] ?? ''));
if ($name === '') api_error(422, 'NAME_REQUIRED', 'Bitte einen Namen angeben.');
if ($id === 0) {
$pdo->prepare('INSERT INTO organizations (name, notes, created_at) VALUES (?,?,?)')
->execute([$name, $notes, db_now()]);
$newId = (int) $pdo->lastInsertId();
audit_log($staff['id'], "Organisation erstellt: {$name} (Mobile App)");
} else {
$pdo->prepare('UPDATE organizations SET name=?, notes=? WHERE id=?')->execute([$name, $notes, $id]);
$newId = $id;
audit_log($staff['id'], "Organisation aktualisiert: {$name} (Mobile App)");
}
api_json(['id' => $newId]);
}
if ($action === 'delete') {
$id = (int) ($body['id'] ?? 0);
$pdo->prepare('UPDATE users SET organization_id = NULL WHERE organization_id = ?')->execute([$id]);
$pdo->prepare('DELETE FROM organizations WHERE id = ?')->execute([$id]);
audit_log($staff['id'], "Organisation gelöscht: #{$id} (Mobile App)");
api_json(['ok' => true]);
}
api_error(422, 'INVALID_ACTION', 'Unbekannte Aktion.');