diff --git a/api.php b/api.php index 343de55..0030d8d 100644 --- a/api.php +++ b/api.php @@ -387,7 +387,7 @@ try { echo json_encode(['success' => true, 'merged' => true]); } else { // Check if a department with the same name exists under the same parent (excluding itself) - $check_stmt = $db->prepare("SELECT id FROM departments WHERE name = ? AND (parent_id <=> ?) AND id != ?"); + $check_stmt = $db->prepare("SELECT id FROM departments WHERE name = ? AND parent_id IS ? AND id != ?"); $check_stmt->execute([$new_name, $parent_id, $dept_id]); $existing = $check_stmt->fetch(); @@ -403,18 +403,32 @@ try { case 'delete_dept': $dept_id = $_GET['id']; - // 1. Find the '미소속' department ID - $miso_id = $db->query("SELECT id FROM departments WHERE name = '미소속'")->fetchColumn(); + + // Find FKI Root + $fki_root = $db->query("SELECT id FROM departments WHERE name = '한국경제인협회' AND parent_id IS NULL LIMIT 1")->fetch(); + $fki_root_id = $fki_root ? $fki_root['id'] : null; + + // 1. Find the '미소속' department under FKI Root + $miso_id = $db->query("SELECT id FROM departments WHERE name = '미소속' AND parent_id IS " . ($fki_root_id ?: 'NULL') . " LIMIT 1")->fetchColumn(); + if (!$miso_id) { - // Fallback creation if not exists - $db->exec("INSERT INTO departments (name, level) VALUES ('미소속', 0)"); + $db->prepare("INSERT INTO departments (name, parent_id, level) VALUES ('미소속', ?, 1)")->execute([$fki_root_id]); $miso_id = $db->lastInsertId(); } - // 2. Move members to '미소속' + // 2. Get current dept info for re-parenting children + $current_dept = $db->prepare("SELECT parent_id FROM departments WHERE id = ?"); + $current_dept->execute([$dept_id]); + $parent_info = $current_dept->fetch(); + $target_new_parent = $parent_info ? $parent_info['parent_id'] : null; + + // 3. Move members to '미소속' $db->prepare("UPDATE users SET department_id = ? WHERE department_id = ?")->execute([$miso_id, $dept_id]); - // 3. Delete the department + // 4. Move child departments to its grandparent (re-parenting) to avoid FK constraint violation + $db->prepare("UPDATE departments SET parent_id = ? WHERE parent_id = ?")->execute([$target_new_parent, $dept_id]); + + // 5. Delete the department $db->prepare("DELETE FROM departments WHERE id = ?")->execute([$dept_id]); echo json_encode(['success' => true]); @@ -582,6 +596,11 @@ try { $updates[] = "department_id = ?"; $params[] = $newDeptId; } + $newPosition = $data['position'] ?? null; + if ($newPosition) { + $updates[] = "position = ?"; + $params[] = $newPosition; + } if (empty($updates)) { echo json_encode(['success' => false, 'error' => 'No updates specified']); diff --git a/departments.php b/departments.php index 2ac6cdf..00d840d 100644 --- a/departments.php +++ b/departments.php @@ -88,10 +88,6 @@