guard = \Closure::fromCallable($guard); } public function dispatch(string $operation, array $data = [], array $query = []): array { if (!preg_match('/^(dept|menu)\.(lists|add|edit|delete)$/D', $operation, $match)) { throw new ApiError(404, '接口不存在'); } [, $kind, $action] = $match; ($this->guard)(); Input::only($query, []); if ($action === 'lists') { Input::only($data, []); return $this->tree($kind); } return $this->store->write(function () use ($kind, $action, $data): array { // 在取得写锁之后再次验证公司启用状态,避免停用与保存并发穿透。 ($this->guard)(); if ($action === 'delete') { return $this->delete($kind, $data); } return $this->save($kind, $action, $data); }); } private function rows(string $kind): array { $rows = $this->store->all('SELECT * FROM company_structure_node WHERE company_id=? AND kind=? ORDER BY sort DESC,id ASC LIMIT ?', [(int) $this->company['id'], $kind, self::MAX_NODES + 1]); if (count($rows) > self::MAX_NODES) { throw new ApiError(422, '公司结构数量超过当前上限'); } return $rows; } private function internalId(mixed $value, string $label = 'id'): int { $id = Input::integer($value, $label, 1, self::MAX_PUBLIC_ID); if ($id <= self::ID_OFFSET) { throw new ApiError(404, '当前公司中不存在该结构节点'); } return $id - self::ID_OFFSET; } private function node(string $kind, int $id): array { return $this->store->one('SELECT * FROM company_structure_node WHERE company_id=? AND kind=? AND id=?', [(int) $this->company['id'], $kind, $id]) ?? throw new ApiError(404, '当前公司中不存在该结构节点'); } private function publicNode(array $row, string $kind): array { $result = ['id' => (int) $row['id'] + self::ID_OFFSET, 'pid' => (int) $row['pid'] === 0 ? 0 : (int) $row['pid'] + self::ID_OFFSET, 'name' => $row['name'], 'sort' => (int) $row['sort'], 'disable' => (int) $row['disable']]; if ($kind === 'menu') { foreach (['type', 'paths', 'component', 'perms', 'icon', 'selected', 'params'] as $field) { $result[$field] = $row[$field]; } foreach (['is_show', 'is_cache'] as $field) { $result[$field] = (int) $row[$field]; } } else { $result += ['leader' => '', 'mobile' => '', 'admin_count' => 0]; } return $result; } private function tree(string $kind): array { $rows = $this->rows($kind); $this->validateTree($rows, $kind); $children = []; foreach ($rows as $row) { $children[(int) $row['pid']][] = $row; } $build = function (int $pid) use (&$build, $children, $kind): array { return array_map(fn (array $row): array => $this->publicNode($row, $kind) + ['children' => $build((int) $row['id'])], $children[$pid] ?? []); }; return $build(0); } /** 校验完整候选树,包含移动后受影响的所有后代深度。 */ private function validateTree(array $rows, string $kind): void { $nodes = []; foreach ($rows as $row) { $nodes[(int) $row['id']] = $row; } foreach ($nodes as $id => $row) { $cursor = $id; $seen = []; while ($cursor !== 0) { if (isset($seen[$cursor]) || count($seen) >= 64) { throw new ApiError(422, '上级节点不能是自己或后代,且层级不能超过64层'); } if (!isset($nodes[$cursor])) { throw new ApiError(422, '上级节点不属于当前公司的同类结构'); } $seen[$cursor] = true; $parent = (int) $nodes[$cursor]['pid']; if ($parent !== 0 && (!isset($nodes[$parent]) || ($kind === 'menu' && $nodes[$parent]['type'] === 'A'))) { throw new ApiError(422, '上级节点不属于当前公司的同类结构,或上级菜单是按钮'); } $cursor = $parent; } } } private function save(string $kind, string $action, array $data): array { $allowed = ['pid', 'name', 'sort', 'disable']; if ($kind === 'menu') { $allowed = [...$allowed, 'type', 'paths', 'component', 'perms', 'icon', 'is_show', 'is_cache', 'selected', 'params']; } Input::only($data, $action === 'edit' ? [...$allowed, 'id'] : $allowed); $id = $action === 'edit' ? $this->internalId($data['id'] ?? null) : 0; $old = $id ? $this->node($kind, $id) : []; // 上级在数据库中保存本地行编号;外部只接收带独立编号段的结构编号。 $pid = array_key_exists('pid', $data) ? Input::integer($data['pid'], '上级编号', 0, self::MAX_PUBLIC_ID) : ((int) ($old['pid'] ?? 0) === 0 ? 0 : (int) $old['pid'] + self::ID_OFFSET); $parent = $pid === 0 ? 0 : $this->internalId($pid, '上级编号'); if ($parent) { $this->node($kind, $parent); } $values = array_replace($old, $data); $payload = ['pid' => $parent, 'name' => Input::text($values['name'] ?? null, '名称', 1, 64), 'sort' => Input::integer($values['sort'] ?? 0, '排序', 0, 1000000), 'disable' => Input::integer($values['disable'] ?? 0, '状态', 0, 1)]; if ($kind === 'menu') { $type = Input::text($values['type'] ?? null, '菜单类型', 1, 1); if (!in_array($type, ['M', 'C', 'A'], true)) { throw new ApiError(422, '菜单类型必须为M/C/A'); } if ($type === 'A' && $parent === 0) { throw new ApiError(422, '按钮必须归属目录或页面'); } $payload += ['type' => $type, 'is_show' => Input::integer($values['is_show'] ?? 1, '显示状态', 0, 1), 'is_cache' => Input::integer($values['is_cache'] ?? 0, '缓存状态', 0, 1)]; foreach (['icon' => 100, 'perms' => 200, 'paths' => 200, 'component' => 200, 'selected' => 200, 'params' => 200] as $field => $max) { $payload[$field] = Input::text($values[$field] ?? '', $field, 0, $max); } $prefix = 'company.' . $this->company['code'] . '.'; if (($payload['perms'] === '' && $type !== 'M') || ($payload['perms'] !== '' && (!str_starts_with($payload['perms'], $prefix) || strlen($payload['perms']) <= strlen($prefix) || !preg_match('~^[A-Za-z0-9._:/-]+$~D', $payload['perms'])))) { throw new ApiError(422, '菜单权限必须使用当前公司的权限前缀,页面和按钮权限不能为空'); } } $rows = $this->rows($kind); if (!$id && count($rows) >= self::MAX_NODES) { throw new ApiError(422, '公司结构数量已达当前上限'); } $candidate = array_replace($old, $payload, ['id' => $id ?: -1]); $rows = array_values(array_filter($rows, static fn (array $row): bool => (int) $row['id'] !== $id)); $rows[] = $candidate; $this->validateTree($rows, $kind); $now = time(); if ($id) { $fields = implode(',', array_map(static fn (string $field): string => $field . '=?', array_keys($payload))); $this->store->execute('UPDATE company_structure_node SET ' . $fields . ',update_time=? WHERE company_id=? AND kind=? AND id=?', [...array_values($payload), $now, (int) $this->company['id'], $kind, $id]); if ($kind === 'menu') { (new KefuMenuCatalog($this->store))->recordEdit($id, array_intersect_key($payload, $data)); } } else { $payload += ['company_id' => (int) $this->company['id'], 'kind' => $kind, 'create_time' => $now, 'update_time' => $now]; $this->store->execute('INSERT INTO company_structure_node(' . implode(',', array_keys($payload)) . ') VALUES(' . implode(',', array_fill(0, count($payload), '?')) . ')', array_values($payload)); $id = (int) $this->store->one('SELECT last_insert_rowid() AS id')['id']; if ($id > self::MAX_PUBLIC_ID - self::ID_OFFSET) { throw new ApiError(422, '公司结构编号已达上限'); } } $this->store->audit($this->actorId, 'structure.' . $kind . '.' . ($action === 'add' ? 'create' : 'update'), (int) $this->company['id'], $id + self::ID_OFFSET); return []; } private function delete(string $kind, array $data): array { Input::only($data, ['id']); $id = $this->internalId($data['id'] ?? null); $this->node($kind, $id); if ($this->store->one('SELECT id FROM company_structure_node WHERE company_id=? AND kind=? AND pid=? LIMIT 1', [(int) $this->company['id'], $kind, $id])) { throw new ApiError(409, '存在子节点,不能删除'); } $this->store->execute('DELETE FROM company_structure_node WHERE company_id=? AND kind=? AND id=?', [(int) $this->company['id'], $kind, $id]); $this->store->audit($this->actorId, 'structure.' . $kind . '.delete', (int) $this->company['id'], $id + self::ID_OFFSET); return []; } }